1 //===-- llvm/CodeGen/GlobalISel/IRTranslator.cpp - IRTranslator --*- C++ -*-==// 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 /// \file 10 /// This file implements the IRTranslator class. 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/CodeGen/GlobalISel/IRTranslator.h" 14 15 #include "llvm/ADT/ScopeExit.h" 16 #include "llvm/ADT/SmallSet.h" 17 #include "llvm/ADT/SmallVector.h" 18 #include "llvm/Analysis/OptimizationDiagnosticInfo.h" 19 #include "llvm/CodeGen/Analysis.h" 20 #include "llvm/CodeGen/GlobalISel/CallLowering.h" 21 #include "llvm/CodeGen/MachineFrameInfo.h" 22 #include "llvm/CodeGen/MachineFunction.h" 23 #include "llvm/CodeGen/MachineModuleInfo.h" 24 #include "llvm/CodeGen/MachineRegisterInfo.h" 25 #include "llvm/CodeGen/TargetPassConfig.h" 26 #include "llvm/IR/Constant.h" 27 #include "llvm/IR/DebugInfo.h" 28 #include "llvm/IR/Function.h" 29 #include "llvm/IR/GetElementPtrTypeIterator.h" 30 #include "llvm/IR/IntrinsicInst.h" 31 #include "llvm/IR/Type.h" 32 #include "llvm/IR/Value.h" 33 #include "llvm/Target/TargetFrameLowering.h" 34 #include "llvm/Target/TargetIntrinsicInfo.h" 35 #include "llvm/Target/TargetLowering.h" 36 37 #define DEBUG_TYPE "irtranslator" 38 39 using namespace llvm; 40 41 char IRTranslator::ID = 0; 42 INITIALIZE_PASS_BEGIN(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI", 43 false, false) 44 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig) 45 INITIALIZE_PASS_END(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI", 46 false, false) 47 48 static void reportTranslationError(MachineFunction &MF, 49 const TargetPassConfig &TPC, 50 OptimizationRemarkEmitter &ORE, 51 OptimizationRemarkMissed &R) { 52 MF.getProperties().set(MachineFunctionProperties::Property::FailedISel); 53 54 // Print the function name explicitly if we don't have a debug location (which 55 // makes the diagnostic less useful) or if we're going to emit a raw error. 56 if (!R.getLocation().isValid() || TPC.isGlobalISelAbortEnabled()) 57 R << (" (in function: " + MF.getName() + ")").str(); 58 59 if (TPC.isGlobalISelAbortEnabled()) 60 report_fatal_error(R.getMsg()); 61 else 62 ORE.emit(R); 63 } 64 65 IRTranslator::IRTranslator() : MachineFunctionPass(ID), MRI(nullptr) { 66 initializeIRTranslatorPass(*PassRegistry::getPassRegistry()); 67 } 68 69 void IRTranslator::getAnalysisUsage(AnalysisUsage &AU) const { 70 AU.addRequired<TargetPassConfig>(); 71 MachineFunctionPass::getAnalysisUsage(AU); 72 } 73 74 75 unsigned IRTranslator::getOrCreateVReg(const Value &Val) { 76 unsigned &ValReg = ValToVReg[&Val]; 77 78 if (ValReg) 79 return ValReg; 80 81 // Fill ValRegsSequence with the sequence of registers 82 // we need to concat together to produce the value. 83 assert(Val.getType()->isSized() && 84 "Don't know how to create an empty vreg"); 85 unsigned VReg = 86 MRI->createGenericVirtualRegister(getLLTForType(*Val.getType(), *DL)); 87 ValReg = VReg; 88 89 if (auto CV = dyn_cast<Constant>(&Val)) { 90 bool Success = translate(*CV, VReg); 91 if (!Success) { 92 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure", 93 MF->getFunction()->getSubprogram(), 94 &MF->getFunction()->getEntryBlock()); 95 R << "unable to translate constant: " << ore::NV("Type", Val.getType()); 96 reportTranslationError(*MF, *TPC, *ORE, R); 97 return VReg; 98 } 99 } 100 101 return VReg; 102 } 103 104 int IRTranslator::getOrCreateFrameIndex(const AllocaInst &AI) { 105 if (FrameIndices.find(&AI) != FrameIndices.end()) 106 return FrameIndices[&AI]; 107 108 unsigned ElementSize = DL->getTypeStoreSize(AI.getAllocatedType()); 109 unsigned Size = 110 ElementSize * cast<ConstantInt>(AI.getArraySize())->getZExtValue(); 111 112 // Always allocate at least one byte. 113 Size = std::max(Size, 1u); 114 115 unsigned Alignment = AI.getAlignment(); 116 if (!Alignment) 117 Alignment = DL->getABITypeAlignment(AI.getAllocatedType()); 118 119 int &FI = FrameIndices[&AI]; 120 FI = MF->getFrameInfo().CreateStackObject(Size, Alignment, false, &AI); 121 return FI; 122 } 123 124 unsigned IRTranslator::getMemOpAlignment(const Instruction &I) { 125 unsigned Alignment = 0; 126 Type *ValTy = nullptr; 127 if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) { 128 Alignment = SI->getAlignment(); 129 ValTy = SI->getValueOperand()->getType(); 130 } else if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) { 131 Alignment = LI->getAlignment(); 132 ValTy = LI->getType(); 133 } else { 134 OptimizationRemarkMissed R("gisel-irtranslator", "", &I); 135 R << "unable to translate memop: " << ore::NV("Opcode", &I); 136 reportTranslationError(*MF, *TPC, *ORE, R); 137 return 1; 138 } 139 140 return Alignment ? Alignment : DL->getABITypeAlignment(ValTy); 141 } 142 143 MachineBasicBlock &IRTranslator::getMBB(const BasicBlock &BB) { 144 MachineBasicBlock *&MBB = BBToMBB[&BB]; 145 assert(MBB && "BasicBlock was not encountered before"); 146 return *MBB; 147 } 148 149 void IRTranslator::addMachineCFGPred(CFGEdge Edge, MachineBasicBlock *NewPred) { 150 assert(NewPred && "new predecessor must be a real MachineBasicBlock"); 151 MachinePreds[Edge].push_back(NewPred); 152 } 153 154 bool IRTranslator::translateBinaryOp(unsigned Opcode, const User &U, 155 MachineIRBuilder &MIRBuilder) { 156 // FIXME: handle signed/unsigned wrapping flags. 157 158 // Get or create a virtual register for each value. 159 // Unless the value is a Constant => loadimm cst? 160 // or inline constant each time? 161 // Creation of a virtual register needs to have a size. 162 unsigned Op0 = getOrCreateVReg(*U.getOperand(0)); 163 unsigned Op1 = getOrCreateVReg(*U.getOperand(1)); 164 unsigned Res = getOrCreateVReg(U); 165 MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op0).addUse(Op1); 166 return true; 167 } 168 169 bool IRTranslator::translateFSub(const User &U, MachineIRBuilder &MIRBuilder) { 170 // -0.0 - X --> G_FNEG 171 if (isa<Constant>(U.getOperand(0)) && 172 U.getOperand(0) == ConstantFP::getZeroValueForNegation(U.getType())) { 173 MIRBuilder.buildInstr(TargetOpcode::G_FNEG) 174 .addDef(getOrCreateVReg(U)) 175 .addUse(getOrCreateVReg(*U.getOperand(1))); 176 return true; 177 } 178 return translateBinaryOp(TargetOpcode::G_FSUB, U, MIRBuilder); 179 } 180 181 bool IRTranslator::translateCompare(const User &U, 182 MachineIRBuilder &MIRBuilder) { 183 const CmpInst *CI = dyn_cast<CmpInst>(&U); 184 unsigned Op0 = getOrCreateVReg(*U.getOperand(0)); 185 unsigned Op1 = getOrCreateVReg(*U.getOperand(1)); 186 unsigned Res = getOrCreateVReg(U); 187 CmpInst::Predicate Pred = 188 CI ? CI->getPredicate() : static_cast<CmpInst::Predicate>( 189 cast<ConstantExpr>(U).getPredicate()); 190 if (CmpInst::isIntPredicate(Pred)) 191 MIRBuilder.buildICmp(Pred, Res, Op0, Op1); 192 else if (Pred == CmpInst::FCMP_FALSE) 193 MIRBuilder.buildCopy( 194 Res, getOrCreateVReg(*Constant::getNullValue(CI->getType()))); 195 else if (Pred == CmpInst::FCMP_TRUE) 196 MIRBuilder.buildCopy( 197 Res, getOrCreateVReg(*Constant::getAllOnesValue(CI->getType()))); 198 else 199 MIRBuilder.buildFCmp(Pred, Res, Op0, Op1); 200 201 return true; 202 } 203 204 bool IRTranslator::translateRet(const User &U, MachineIRBuilder &MIRBuilder) { 205 const ReturnInst &RI = cast<ReturnInst>(U); 206 const Value *Ret = RI.getReturnValue(); 207 // The target may mess up with the insertion point, but 208 // this is not important as a return is the last instruction 209 // of the block anyway. 210 return CLI->lowerReturn(MIRBuilder, Ret, !Ret ? 0 : getOrCreateVReg(*Ret)); 211 } 212 213 bool IRTranslator::translateBr(const User &U, MachineIRBuilder &MIRBuilder) { 214 const BranchInst &BrInst = cast<BranchInst>(U); 215 unsigned Succ = 0; 216 if (!BrInst.isUnconditional()) { 217 // We want a G_BRCOND to the true BB followed by an unconditional branch. 218 unsigned Tst = getOrCreateVReg(*BrInst.getCondition()); 219 const BasicBlock &TrueTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ++)); 220 MachineBasicBlock &TrueBB = getMBB(TrueTgt); 221 MIRBuilder.buildBrCond(Tst, TrueBB); 222 } 223 224 const BasicBlock &BrTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ)); 225 MachineBasicBlock &TgtBB = getMBB(BrTgt); 226 MachineBasicBlock &CurBB = MIRBuilder.getMBB(); 227 228 // If the unconditional target is the layout successor, fallthrough. 229 if (!CurBB.isLayoutSuccessor(&TgtBB)) 230 MIRBuilder.buildBr(TgtBB); 231 232 // Link successors. 233 for (const BasicBlock *Succ : BrInst.successors()) 234 CurBB.addSuccessor(&getMBB(*Succ)); 235 return true; 236 } 237 238 bool IRTranslator::translateSwitch(const User &U, 239 MachineIRBuilder &MIRBuilder) { 240 // For now, just translate as a chain of conditional branches. 241 // FIXME: could we share most of the logic/code in 242 // SelectionDAGBuilder::visitSwitch between SelectionDAG and GlobalISel? 243 // At first sight, it seems most of the logic in there is independent of 244 // SelectionDAG-specifics and a lot of work went in to optimize switch 245 // lowering in there. 246 247 const SwitchInst &SwInst = cast<SwitchInst>(U); 248 const unsigned SwCondValue = getOrCreateVReg(*SwInst.getCondition()); 249 const BasicBlock *OrigBB = SwInst.getParent(); 250 251 LLT LLTi1 = getLLTForType(*Type::getInt1Ty(U.getContext()), *DL); 252 for (auto &CaseIt : SwInst.cases()) { 253 const unsigned CaseValueReg = getOrCreateVReg(*CaseIt.getCaseValue()); 254 const unsigned Tst = MRI->createGenericVirtualRegister(LLTi1); 255 MIRBuilder.buildICmp(CmpInst::ICMP_EQ, Tst, CaseValueReg, SwCondValue); 256 MachineBasicBlock &CurMBB = MIRBuilder.getMBB(); 257 const BasicBlock *TrueBB = CaseIt.getCaseSuccessor(); 258 MachineBasicBlock &TrueMBB = getMBB(*TrueBB); 259 260 MIRBuilder.buildBrCond(Tst, TrueMBB); 261 CurMBB.addSuccessor(&TrueMBB); 262 addMachineCFGPred({OrigBB, TrueBB}, &CurMBB); 263 264 MachineBasicBlock *FalseMBB = 265 MF->CreateMachineBasicBlock(SwInst.getParent()); 266 // Insert the comparison blocks one after the other. 267 MF->insert(std::next(CurMBB.getIterator()), FalseMBB); 268 MIRBuilder.buildBr(*FalseMBB); 269 CurMBB.addSuccessor(FalseMBB); 270 271 MIRBuilder.setMBB(*FalseMBB); 272 } 273 // handle default case 274 const BasicBlock *DefaultBB = SwInst.getDefaultDest(); 275 MachineBasicBlock &DefaultMBB = getMBB(*DefaultBB); 276 MIRBuilder.buildBr(DefaultMBB); 277 MachineBasicBlock &CurMBB = MIRBuilder.getMBB(); 278 CurMBB.addSuccessor(&DefaultMBB); 279 addMachineCFGPred({OrigBB, DefaultBB}, &CurMBB); 280 281 return true; 282 } 283 284 bool IRTranslator::translateIndirectBr(const User &U, 285 MachineIRBuilder &MIRBuilder) { 286 const IndirectBrInst &BrInst = cast<IndirectBrInst>(U); 287 288 const unsigned Tgt = getOrCreateVReg(*BrInst.getAddress()); 289 MIRBuilder.buildBrIndirect(Tgt); 290 291 // Link successors. 292 MachineBasicBlock &CurBB = MIRBuilder.getMBB(); 293 for (const BasicBlock *Succ : BrInst.successors()) 294 CurBB.addSuccessor(&getMBB(*Succ)); 295 296 return true; 297 } 298 299 bool IRTranslator::translateLoad(const User &U, MachineIRBuilder &MIRBuilder) { 300 const LoadInst &LI = cast<LoadInst>(U); 301 302 auto Flags = LI.isVolatile() ? MachineMemOperand::MOVolatile 303 : MachineMemOperand::MONone; 304 Flags |= MachineMemOperand::MOLoad; 305 306 unsigned Res = getOrCreateVReg(LI); 307 unsigned Addr = getOrCreateVReg(*LI.getPointerOperand()); 308 309 MIRBuilder.buildLoad( 310 Res, Addr, 311 *MF->getMachineMemOperand(MachinePointerInfo(LI.getPointerOperand()), 312 Flags, DL->getTypeStoreSize(LI.getType()), 313 getMemOpAlignment(LI), AAMDNodes(), nullptr, 314 LI.getSynchScope(), LI.getOrdering())); 315 return true; 316 } 317 318 bool IRTranslator::translateStore(const User &U, MachineIRBuilder &MIRBuilder) { 319 const StoreInst &SI = cast<StoreInst>(U); 320 auto Flags = SI.isVolatile() ? MachineMemOperand::MOVolatile 321 : MachineMemOperand::MONone; 322 Flags |= MachineMemOperand::MOStore; 323 324 unsigned Val = getOrCreateVReg(*SI.getValueOperand()); 325 unsigned Addr = getOrCreateVReg(*SI.getPointerOperand()); 326 327 MIRBuilder.buildStore( 328 Val, Addr, 329 *MF->getMachineMemOperand( 330 MachinePointerInfo(SI.getPointerOperand()), Flags, 331 DL->getTypeStoreSize(SI.getValueOperand()->getType()), 332 getMemOpAlignment(SI), AAMDNodes(), nullptr, SI.getSynchScope(), 333 SI.getOrdering())); 334 return true; 335 } 336 337 bool IRTranslator::translateExtractValue(const User &U, 338 MachineIRBuilder &MIRBuilder) { 339 const Value *Src = U.getOperand(0); 340 Type *Int32Ty = Type::getInt32Ty(U.getContext()); 341 SmallVector<Value *, 1> Indices; 342 343 // If Src is a single element ConstantStruct, translate extractvalue 344 // to that element to avoid inserting a cast instruction. 345 if (auto CS = dyn_cast<ConstantStruct>(Src)) 346 if (CS->getNumOperands() == 1) { 347 unsigned Res = getOrCreateVReg(*CS->getOperand(0)); 348 ValToVReg[&U] = Res; 349 return true; 350 } 351 352 // getIndexedOffsetInType is designed for GEPs, so the first index is the 353 // usual array element rather than looking into the actual aggregate. 354 Indices.push_back(ConstantInt::get(Int32Ty, 0)); 355 356 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) { 357 for (auto Idx : EVI->indices()) 358 Indices.push_back(ConstantInt::get(Int32Ty, Idx)); 359 } else { 360 for (unsigned i = 1; i < U.getNumOperands(); ++i) 361 Indices.push_back(U.getOperand(i)); 362 } 363 364 uint64_t Offset = 8 * DL->getIndexedOffsetInType(Src->getType(), Indices); 365 366 unsigned Res = getOrCreateVReg(U); 367 MIRBuilder.buildExtract(Res, getOrCreateVReg(*Src), Offset); 368 369 return true; 370 } 371 372 bool IRTranslator::translateInsertValue(const User &U, 373 MachineIRBuilder &MIRBuilder) { 374 const Value *Src = U.getOperand(0); 375 Type *Int32Ty = Type::getInt32Ty(U.getContext()); 376 SmallVector<Value *, 1> Indices; 377 378 // getIndexedOffsetInType is designed for GEPs, so the first index is the 379 // usual array element rather than looking into the actual aggregate. 380 Indices.push_back(ConstantInt::get(Int32Ty, 0)); 381 382 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) { 383 for (auto Idx : IVI->indices()) 384 Indices.push_back(ConstantInt::get(Int32Ty, Idx)); 385 } else { 386 for (unsigned i = 2; i < U.getNumOperands(); ++i) 387 Indices.push_back(U.getOperand(i)); 388 } 389 390 uint64_t Offset = 8 * DL->getIndexedOffsetInType(Src->getType(), Indices); 391 392 unsigned Res = getOrCreateVReg(U); 393 unsigned Inserted = getOrCreateVReg(*U.getOperand(1)); 394 MIRBuilder.buildInsert(Res, getOrCreateVReg(*Src), Inserted, Offset); 395 396 return true; 397 } 398 399 bool IRTranslator::translateSelect(const User &U, 400 MachineIRBuilder &MIRBuilder) { 401 unsigned Res = getOrCreateVReg(U); 402 unsigned Tst = getOrCreateVReg(*U.getOperand(0)); 403 unsigned Op0 = getOrCreateVReg(*U.getOperand(1)); 404 unsigned Op1 = getOrCreateVReg(*U.getOperand(2)); 405 MIRBuilder.buildSelect(Res, Tst, Op0, Op1); 406 return true; 407 } 408 409 bool IRTranslator::translateBitCast(const User &U, 410 MachineIRBuilder &MIRBuilder) { 411 // If we're bitcasting to the source type, we can reuse the source vreg. 412 if (getLLTForType(*U.getOperand(0)->getType(), *DL) == 413 getLLTForType(*U.getType(), *DL)) { 414 // Get the source vreg now, to avoid invalidating ValToVReg. 415 unsigned SrcReg = getOrCreateVReg(*U.getOperand(0)); 416 unsigned &Reg = ValToVReg[&U]; 417 // If we already assigned a vreg for this bitcast, we can't change that. 418 // Emit a copy to satisfy the users we already emitted. 419 if (Reg) 420 MIRBuilder.buildCopy(Reg, SrcReg); 421 else 422 Reg = SrcReg; 423 return true; 424 } 425 return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder); 426 } 427 428 bool IRTranslator::translateCast(unsigned Opcode, const User &U, 429 MachineIRBuilder &MIRBuilder) { 430 unsigned Op = getOrCreateVReg(*U.getOperand(0)); 431 unsigned Res = getOrCreateVReg(U); 432 MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op); 433 return true; 434 } 435 436 bool IRTranslator::translateGetElementPtr(const User &U, 437 MachineIRBuilder &MIRBuilder) { 438 // FIXME: support vector GEPs. 439 if (U.getType()->isVectorTy()) 440 return false; 441 442 Value &Op0 = *U.getOperand(0); 443 unsigned BaseReg = getOrCreateVReg(Op0); 444 Type *PtrIRTy = Op0.getType(); 445 LLT PtrTy = getLLTForType(*PtrIRTy, *DL); 446 Type *OffsetIRTy = DL->getIntPtrType(PtrIRTy); 447 LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL); 448 449 int64_t Offset = 0; 450 for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U); 451 GTI != E; ++GTI) { 452 const Value *Idx = GTI.getOperand(); 453 if (StructType *StTy = GTI.getStructTypeOrNull()) { 454 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 455 Offset += DL->getStructLayout(StTy)->getElementOffset(Field); 456 continue; 457 } else { 458 uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType()); 459 460 // If this is a scalar constant or a splat vector of constants, 461 // handle it quickly. 462 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) { 463 Offset += ElementSize * CI->getSExtValue(); 464 continue; 465 } 466 467 if (Offset != 0) { 468 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy); 469 unsigned OffsetReg = 470 getOrCreateVReg(*ConstantInt::get(OffsetIRTy, Offset)); 471 MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg); 472 473 BaseReg = NewBaseReg; 474 Offset = 0; 475 } 476 477 // N = N + Idx * ElementSize; 478 unsigned ElementSizeReg = 479 getOrCreateVReg(*ConstantInt::get(OffsetIRTy, ElementSize)); 480 481 unsigned IdxReg = getOrCreateVReg(*Idx); 482 if (MRI->getType(IdxReg) != OffsetTy) { 483 unsigned NewIdxReg = MRI->createGenericVirtualRegister(OffsetTy); 484 MIRBuilder.buildSExtOrTrunc(NewIdxReg, IdxReg); 485 IdxReg = NewIdxReg; 486 } 487 488 unsigned OffsetReg = MRI->createGenericVirtualRegister(OffsetTy); 489 MIRBuilder.buildMul(OffsetReg, ElementSizeReg, IdxReg); 490 491 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy); 492 MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg); 493 BaseReg = NewBaseReg; 494 } 495 } 496 497 if (Offset != 0) { 498 unsigned OffsetReg = getOrCreateVReg(*ConstantInt::get(OffsetIRTy, Offset)); 499 MIRBuilder.buildGEP(getOrCreateVReg(U), BaseReg, OffsetReg); 500 return true; 501 } 502 503 MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg); 504 return true; 505 } 506 507 bool IRTranslator::translateMemfunc(const CallInst &CI, 508 MachineIRBuilder &MIRBuilder, 509 unsigned ID) { 510 LLT SizeTy = getLLTForType(*CI.getArgOperand(2)->getType(), *DL); 511 Type *DstTy = CI.getArgOperand(0)->getType(); 512 if (cast<PointerType>(DstTy)->getAddressSpace() != 0 || 513 SizeTy.getSizeInBits() != DL->getPointerSizeInBits(0)) 514 return false; 515 516 SmallVector<CallLowering::ArgInfo, 8> Args; 517 for (int i = 0; i < 3; ++i) { 518 const auto &Arg = CI.getArgOperand(i); 519 Args.emplace_back(getOrCreateVReg(*Arg), Arg->getType()); 520 } 521 522 const char *Callee; 523 switch (ID) { 524 case Intrinsic::memmove: 525 case Intrinsic::memcpy: { 526 Type *SrcTy = CI.getArgOperand(1)->getType(); 527 if(cast<PointerType>(SrcTy)->getAddressSpace() != 0) 528 return false; 529 Callee = ID == Intrinsic::memcpy ? "memcpy" : "memmove"; 530 break; 531 } 532 case Intrinsic::memset: 533 Callee = "memset"; 534 break; 535 default: 536 return false; 537 } 538 539 return CLI->lowerCall(MIRBuilder, CI.getCallingConv(), 540 MachineOperand::CreateES(Callee), 541 CallLowering::ArgInfo(0, CI.getType()), Args); 542 } 543 544 void IRTranslator::getStackGuard(unsigned DstReg, 545 MachineIRBuilder &MIRBuilder) { 546 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo(); 547 MRI->setRegClass(DstReg, TRI->getPointerRegClass(*MF)); 548 auto MIB = MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD); 549 MIB.addDef(DstReg); 550 551 auto &TLI = *MF->getSubtarget().getTargetLowering(); 552 Value *Global = TLI.getSDagStackGuard(*MF->getFunction()->getParent()); 553 if (!Global) 554 return; 555 556 MachinePointerInfo MPInfo(Global); 557 MachineInstr::mmo_iterator MemRefs = MF->allocateMemRefsArray(1); 558 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 559 MachineMemOperand::MODereferenceable; 560 *MemRefs = 561 MF->getMachineMemOperand(MPInfo, Flags, DL->getPointerSizeInBits() / 8, 562 DL->getPointerABIAlignment()); 563 MIB.setMemRefs(MemRefs, MemRefs + 1); 564 } 565 566 bool IRTranslator::translateOverflowIntrinsic(const CallInst &CI, unsigned Op, 567 MachineIRBuilder &MIRBuilder) { 568 LLT Ty = getLLTForType(*CI.getOperand(0)->getType(), *DL); 569 LLT s1 = LLT::scalar(1); 570 unsigned Width = Ty.getSizeInBits(); 571 unsigned Res = MRI->createGenericVirtualRegister(Ty); 572 unsigned Overflow = MRI->createGenericVirtualRegister(s1); 573 auto MIB = MIRBuilder.buildInstr(Op) 574 .addDef(Res) 575 .addDef(Overflow) 576 .addUse(getOrCreateVReg(*CI.getOperand(0))) 577 .addUse(getOrCreateVReg(*CI.getOperand(1))); 578 579 if (Op == TargetOpcode::G_UADDE || Op == TargetOpcode::G_USUBE) { 580 unsigned Zero = getOrCreateVReg( 581 *Constant::getNullValue(Type::getInt1Ty(CI.getContext()))); 582 MIB.addUse(Zero); 583 } 584 585 MIRBuilder.buildSequence(getOrCreateVReg(CI), {Res, Overflow}, {0, Width}); 586 return true; 587 } 588 589 bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID, 590 MachineIRBuilder &MIRBuilder) { 591 switch (ID) { 592 default: 593 break; 594 case Intrinsic::lifetime_start: 595 case Intrinsic::lifetime_end: 596 // Stack coloring is not enabled in O0 (which we care about now) so we can 597 // drop these. Make sure someone notices when we start compiling at higher 598 // opts though. 599 if (MF->getTarget().getOptLevel() != CodeGenOpt::None) 600 return false; 601 return true; 602 case Intrinsic::dbg_declare: { 603 const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI); 604 assert(DI.getVariable() && "Missing variable"); 605 606 const Value *Address = DI.getAddress(); 607 if (!Address || isa<UndefValue>(Address)) { 608 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 609 return true; 610 } 611 612 assert(DI.getVariable()->isValidLocationForIntrinsic( 613 MIRBuilder.getDebugLoc()) && 614 "Expected inlined-at fields to agree"); 615 auto AI = dyn_cast<AllocaInst>(Address); 616 if (AI && AI->isStaticAlloca()) { 617 // Static allocas are tracked at the MF level, no need for DBG_VALUE 618 // instructions (in fact, they get ignored if they *do* exist). 619 MF->setVariableDbgInfo(DI.getVariable(), DI.getExpression(), 620 getOrCreateFrameIndex(*AI), DI.getDebugLoc()); 621 } else 622 MIRBuilder.buildDirectDbgValue(getOrCreateVReg(*Address), 623 DI.getVariable(), DI.getExpression()); 624 return true; 625 } 626 case Intrinsic::vaend: 627 // No target I know of cares about va_end. Certainly no in-tree target 628 // does. Simplest intrinsic ever! 629 return true; 630 case Intrinsic::vastart: { 631 auto &TLI = *MF->getSubtarget().getTargetLowering(); 632 Value *Ptr = CI.getArgOperand(0); 633 unsigned ListSize = TLI.getVaListSizeInBits(*DL) / 8; 634 635 MIRBuilder.buildInstr(TargetOpcode::G_VASTART) 636 .addUse(getOrCreateVReg(*Ptr)) 637 .addMemOperand(MF->getMachineMemOperand( 638 MachinePointerInfo(Ptr), MachineMemOperand::MOStore, ListSize, 0)); 639 return true; 640 } 641 case Intrinsic::dbg_value: { 642 // This form of DBG_VALUE is target-independent. 643 const DbgValueInst &DI = cast<DbgValueInst>(CI); 644 const Value *V = DI.getValue(); 645 assert(DI.getVariable()->isValidLocationForIntrinsic( 646 MIRBuilder.getDebugLoc()) && 647 "Expected inlined-at fields to agree"); 648 if (!V) { 649 // Currently the optimizer can produce this; insert an undef to 650 // help debugging. Probably the optimizer should not do this. 651 MIRBuilder.buildIndirectDbgValue(0, DI.getOffset(), DI.getVariable(), 652 DI.getExpression()); 653 } else if (const auto *CI = dyn_cast<Constant>(V)) { 654 MIRBuilder.buildConstDbgValue(*CI, DI.getOffset(), DI.getVariable(), 655 DI.getExpression()); 656 } else { 657 unsigned Reg = getOrCreateVReg(*V); 658 // FIXME: This does not handle register-indirect values at offset 0. The 659 // direct/indirect thing shouldn't really be handled by something as 660 // implicit as reg+noreg vs reg+imm in the first palce, but it seems 661 // pretty baked in right now. 662 if (DI.getOffset() != 0) 663 MIRBuilder.buildIndirectDbgValue(Reg, DI.getOffset(), DI.getVariable(), 664 DI.getExpression()); 665 else 666 MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(), 667 DI.getExpression()); 668 } 669 return true; 670 } 671 case Intrinsic::uadd_with_overflow: 672 return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDE, MIRBuilder); 673 case Intrinsic::sadd_with_overflow: 674 return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder); 675 case Intrinsic::usub_with_overflow: 676 return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBE, MIRBuilder); 677 case Intrinsic::ssub_with_overflow: 678 return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder); 679 case Intrinsic::umul_with_overflow: 680 return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder); 681 case Intrinsic::smul_with_overflow: 682 return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder); 683 case Intrinsic::pow: 684 MIRBuilder.buildInstr(TargetOpcode::G_FPOW) 685 .addDef(getOrCreateVReg(CI)) 686 .addUse(getOrCreateVReg(*CI.getArgOperand(0))) 687 .addUse(getOrCreateVReg(*CI.getArgOperand(1))); 688 return true; 689 case Intrinsic::fma: 690 MIRBuilder.buildInstr(TargetOpcode::G_FMA) 691 .addDef(getOrCreateVReg(CI)) 692 .addUse(getOrCreateVReg(*CI.getArgOperand(0))) 693 .addUse(getOrCreateVReg(*CI.getArgOperand(1))) 694 .addUse(getOrCreateVReg(*CI.getArgOperand(2))); 695 return true; 696 case Intrinsic::memcpy: 697 case Intrinsic::memmove: 698 case Intrinsic::memset: 699 return translateMemfunc(CI, MIRBuilder, ID); 700 case Intrinsic::eh_typeid_for: { 701 GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0)); 702 unsigned Reg = getOrCreateVReg(CI); 703 unsigned TypeID = MF->getTypeIDFor(GV); 704 MIRBuilder.buildConstant(Reg, TypeID); 705 return true; 706 } 707 case Intrinsic::objectsize: { 708 // If we don't know by now, we're never going to know. 709 const ConstantInt *Min = cast<ConstantInt>(CI.getArgOperand(1)); 710 711 MIRBuilder.buildConstant(getOrCreateVReg(CI), Min->isZero() ? -1ULL : 0); 712 return true; 713 } 714 case Intrinsic::stackguard: 715 getStackGuard(getOrCreateVReg(CI), MIRBuilder); 716 return true; 717 case Intrinsic::stackprotector: { 718 LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL); 719 unsigned GuardVal = MRI->createGenericVirtualRegister(PtrTy); 720 getStackGuard(GuardVal, MIRBuilder); 721 722 AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1)); 723 MIRBuilder.buildStore( 724 GuardVal, getOrCreateVReg(*Slot), 725 *MF->getMachineMemOperand( 726 MachinePointerInfo::getFixedStack(*MF, 727 getOrCreateFrameIndex(*Slot)), 728 MachineMemOperand::MOStore | MachineMemOperand::MOVolatile, 729 PtrTy.getSizeInBits() / 8, 8)); 730 return true; 731 } 732 } 733 return false; 734 } 735 736 bool IRTranslator::translateInlineAsm(const CallInst &CI, 737 MachineIRBuilder &MIRBuilder) { 738 const InlineAsm &IA = cast<InlineAsm>(*CI.getCalledValue()); 739 if (!IA.getConstraintString().empty()) 740 return false; 741 742 unsigned ExtraInfo = 0; 743 if (IA.hasSideEffects()) 744 ExtraInfo |= InlineAsm::Extra_HasSideEffects; 745 if (IA.getDialect() == InlineAsm::AD_Intel) 746 ExtraInfo |= InlineAsm::Extra_AsmDialect; 747 748 MIRBuilder.buildInstr(TargetOpcode::INLINEASM) 749 .addExternalSymbol(IA.getAsmString().c_str()) 750 .addImm(ExtraInfo); 751 752 return true; 753 } 754 755 bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) { 756 const CallInst &CI = cast<CallInst>(U); 757 auto TII = MF->getTarget().getIntrinsicInfo(); 758 const Function *F = CI.getCalledFunction(); 759 760 if (CI.isInlineAsm()) 761 return translateInlineAsm(CI, MIRBuilder); 762 763 if (!F || !F->isIntrinsic()) { 764 unsigned Res = CI.getType()->isVoidTy() ? 0 : getOrCreateVReg(CI); 765 SmallVector<unsigned, 8> Args; 766 for (auto &Arg: CI.arg_operands()) 767 Args.push_back(getOrCreateVReg(*Arg)); 768 769 MF->getFrameInfo().setHasCalls(true); 770 return CLI->lowerCall(MIRBuilder, &CI, Res, Args, [&]() { 771 return getOrCreateVReg(*CI.getCalledValue()); 772 }); 773 } 774 775 Intrinsic::ID ID = F->getIntrinsicID(); 776 if (TII && ID == Intrinsic::not_intrinsic) 777 ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F)); 778 779 assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic"); 780 781 if (translateKnownIntrinsic(CI, ID, MIRBuilder)) 782 return true; 783 784 unsigned Res = CI.getType()->isVoidTy() ? 0 : getOrCreateVReg(CI); 785 MachineInstrBuilder MIB = 786 MIRBuilder.buildIntrinsic(ID, Res, !CI.doesNotAccessMemory()); 787 788 for (auto &Arg : CI.arg_operands()) { 789 // Some intrinsics take metadata parameters. Reject them. 790 if (isa<MetadataAsValue>(Arg)) 791 return false; 792 MIB.addUse(getOrCreateVReg(*Arg)); 793 } 794 795 // Add a MachineMemOperand if it is a target mem intrinsic. 796 const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering(); 797 TargetLowering::IntrinsicInfo Info; 798 // TODO: Add a GlobalISel version of getTgtMemIntrinsic. 799 if (TLI.getTgtMemIntrinsic(Info, CI, ID)) { 800 MachineMemOperand::Flags Flags = 801 Info.vol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 802 Flags |= 803 Info.readMem ? MachineMemOperand::MOLoad : MachineMemOperand::MOStore; 804 uint64_t Size = Info.memVT.getSizeInBits() >> 3; 805 MIB.addMemOperand(MF->getMachineMemOperand(MachinePointerInfo(Info.ptrVal), 806 Flags, Size, Info.align)); 807 } 808 809 return true; 810 } 811 812 bool IRTranslator::translateInvoke(const User &U, 813 MachineIRBuilder &MIRBuilder) { 814 const InvokeInst &I = cast<InvokeInst>(U); 815 MCContext &Context = MF->getContext(); 816 817 const BasicBlock *ReturnBB = I.getSuccessor(0); 818 const BasicBlock *EHPadBB = I.getSuccessor(1); 819 820 const Value *Callee = I.getCalledValue(); 821 const Function *Fn = dyn_cast<Function>(Callee); 822 if (isa<InlineAsm>(Callee)) 823 return false; 824 825 // FIXME: support invoking patchpoint and statepoint intrinsics. 826 if (Fn && Fn->isIntrinsic()) 827 return false; 828 829 // FIXME: support whatever these are. 830 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 831 return false; 832 833 // FIXME: support Windows exception handling. 834 if (!isa<LandingPadInst>(EHPadBB->front())) 835 return false; 836 837 838 // Emit the actual call, bracketed by EH_LABELs so that the MF knows about 839 // the region covered by the try. 840 MCSymbol *BeginSymbol = Context.createTempSymbol(); 841 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol); 842 843 unsigned Res = I.getType()->isVoidTy() ? 0 : getOrCreateVReg(I); 844 SmallVector<unsigned, 8> Args; 845 for (auto &Arg: I.arg_operands()) 846 Args.push_back(getOrCreateVReg(*Arg)); 847 848 if (!CLI->lowerCall(MIRBuilder, &I, Res, Args, 849 [&]() { return getOrCreateVReg(*I.getCalledValue()); })) 850 return false; 851 852 MCSymbol *EndSymbol = Context.createTempSymbol(); 853 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol); 854 855 // FIXME: track probabilities. 856 MachineBasicBlock &EHPadMBB = getMBB(*EHPadBB), 857 &ReturnMBB = getMBB(*ReturnBB); 858 MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol); 859 MIRBuilder.getMBB().addSuccessor(&ReturnMBB); 860 MIRBuilder.getMBB().addSuccessor(&EHPadMBB); 861 MIRBuilder.buildBr(ReturnMBB); 862 863 return true; 864 } 865 866 bool IRTranslator::translateLandingPad(const User &U, 867 MachineIRBuilder &MIRBuilder) { 868 const LandingPadInst &LP = cast<LandingPadInst>(U); 869 870 MachineBasicBlock &MBB = MIRBuilder.getMBB(); 871 addLandingPadInfo(LP, MBB); 872 873 MBB.setIsEHPad(); 874 875 // If there aren't registers to copy the values into (e.g., during SjLj 876 // exceptions), then don't bother. 877 auto &TLI = *MF->getSubtarget().getTargetLowering(); 878 const Constant *PersonalityFn = MF->getFunction()->getPersonalityFn(); 879 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 880 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 881 return true; 882 883 // If landingpad's return type is token type, we don't create DAG nodes 884 // for its exception pointer and selector value. The extraction of exception 885 // pointer or selector value from token type landingpads is not currently 886 // supported. 887 if (LP.getType()->isTokenTy()) 888 return true; 889 890 // Add a label to mark the beginning of the landing pad. Deletion of the 891 // landing pad can thus be detected via the MachineModuleInfo. 892 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL) 893 .addSym(MF->addLandingPad(&MBB)); 894 895 LLT Ty = getLLTForType(*LP.getType(), *DL); 896 unsigned Undef = MRI->createGenericVirtualRegister(Ty); 897 MIRBuilder.buildUndef(Undef); 898 899 SmallVector<LLT, 2> Tys; 900 for (Type *Ty : cast<StructType>(LP.getType())->elements()) 901 Tys.push_back(getLLTForType(*Ty, *DL)); 902 assert(Tys.size() == 2 && "Only two-valued landingpads are supported"); 903 904 // Mark exception register as live in. 905 unsigned ExceptionReg = TLI.getExceptionPointerRegister(PersonalityFn); 906 if (!ExceptionReg) 907 return false; 908 909 MBB.addLiveIn(ExceptionReg); 910 unsigned VReg = MRI->createGenericVirtualRegister(Tys[0]), 911 Tmp = MRI->createGenericVirtualRegister(Ty); 912 MIRBuilder.buildCopy(VReg, ExceptionReg); 913 MIRBuilder.buildInsert(Tmp, Undef, VReg, 0); 914 915 unsigned SelectorReg = TLI.getExceptionSelectorRegister(PersonalityFn); 916 if (!SelectorReg) 917 return false; 918 919 MBB.addLiveIn(SelectorReg); 920 921 // N.b. the exception selector register always has pointer type and may not 922 // match the actual IR-level type in the landingpad so an extra cast is 923 // needed. 924 unsigned PtrVReg = MRI->createGenericVirtualRegister(Tys[0]); 925 MIRBuilder.buildCopy(PtrVReg, SelectorReg); 926 927 VReg = MRI->createGenericVirtualRegister(Tys[1]); 928 MIRBuilder.buildInstr(TargetOpcode::G_PTRTOINT).addDef(VReg).addUse(PtrVReg); 929 MIRBuilder.buildInsert(getOrCreateVReg(LP), Tmp, VReg, 930 Tys[0].getSizeInBits()); 931 return true; 932 } 933 934 bool IRTranslator::translateAlloca(const User &U, 935 MachineIRBuilder &MIRBuilder) { 936 auto &AI = cast<AllocaInst>(U); 937 938 if (AI.isStaticAlloca()) { 939 unsigned Res = getOrCreateVReg(AI); 940 int FI = getOrCreateFrameIndex(AI); 941 MIRBuilder.buildFrameIndex(Res, FI); 942 return true; 943 } 944 945 // Now we're in the harder dynamic case. 946 Type *Ty = AI.getAllocatedType(); 947 unsigned Align = 948 std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI.getAlignment()); 949 950 unsigned NumElts = getOrCreateVReg(*AI.getArraySize()); 951 952 Type *IntPtrIRTy = DL->getIntPtrType(AI.getType()); 953 LLT IntPtrTy = getLLTForType(*IntPtrIRTy, *DL); 954 if (MRI->getType(NumElts) != IntPtrTy) { 955 unsigned ExtElts = MRI->createGenericVirtualRegister(IntPtrTy); 956 MIRBuilder.buildZExtOrTrunc(ExtElts, NumElts); 957 NumElts = ExtElts; 958 } 959 960 unsigned AllocSize = MRI->createGenericVirtualRegister(IntPtrTy); 961 unsigned TySize = 962 getOrCreateVReg(*ConstantInt::get(IntPtrIRTy, -DL->getTypeAllocSize(Ty))); 963 MIRBuilder.buildMul(AllocSize, NumElts, TySize); 964 965 LLT PtrTy = getLLTForType(*AI.getType(), *DL); 966 auto &TLI = *MF->getSubtarget().getTargetLowering(); 967 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore(); 968 969 unsigned SPTmp = MRI->createGenericVirtualRegister(PtrTy); 970 MIRBuilder.buildCopy(SPTmp, SPReg); 971 972 unsigned AllocTmp = MRI->createGenericVirtualRegister(PtrTy); 973 MIRBuilder.buildGEP(AllocTmp, SPTmp, AllocSize); 974 975 // Handle alignment. We have to realign if the allocation granule was smaller 976 // than stack alignment, or the specific alloca requires more than stack 977 // alignment. 978 unsigned StackAlign = 979 MF->getSubtarget().getFrameLowering()->getStackAlignment(); 980 Align = std::max(Align, StackAlign); 981 if (Align > StackAlign || DL->getTypeAllocSize(Ty) % StackAlign != 0) { 982 // Round the size of the allocation up to the stack alignment size 983 // by add SA-1 to the size. This doesn't overflow because we're computing 984 // an address inside an alloca. 985 unsigned AlignedAlloc = MRI->createGenericVirtualRegister(PtrTy); 986 MIRBuilder.buildPtrMask(AlignedAlloc, AllocTmp, Log2_32(Align)); 987 AllocTmp = AlignedAlloc; 988 } 989 990 MIRBuilder.buildCopy(SPReg, AllocTmp); 991 MIRBuilder.buildCopy(getOrCreateVReg(AI), AllocTmp); 992 993 MF->getFrameInfo().CreateVariableSizedObject(Align ? Align : 1, &AI); 994 assert(MF->getFrameInfo().hasVarSizedObjects()); 995 return true; 996 } 997 998 bool IRTranslator::translateVAArg(const User &U, MachineIRBuilder &MIRBuilder) { 999 // FIXME: We may need more info about the type. Because of how LLT works, 1000 // we're completely discarding the i64/double distinction here (amongst 1001 // others). Fortunately the ABIs I know of where that matters don't use va_arg 1002 // anyway but that's not guaranteed. 1003 MIRBuilder.buildInstr(TargetOpcode::G_VAARG) 1004 .addDef(getOrCreateVReg(U)) 1005 .addUse(getOrCreateVReg(*U.getOperand(0))) 1006 .addImm(DL->getABITypeAlignment(U.getType())); 1007 return true; 1008 } 1009 1010 bool IRTranslator::translateInsertElement(const User &U, 1011 MachineIRBuilder &MIRBuilder) { 1012 // If it is a <1 x Ty> vector, use the scalar as it is 1013 // not a legal vector type in LLT. 1014 if (U.getType()->getVectorNumElements() == 1) { 1015 unsigned Elt = getOrCreateVReg(*U.getOperand(1)); 1016 ValToVReg[&U] = Elt; 1017 return true; 1018 } 1019 unsigned Res = getOrCreateVReg(U); 1020 unsigned Val = getOrCreateVReg(*U.getOperand(0)); 1021 unsigned Elt = getOrCreateVReg(*U.getOperand(1)); 1022 unsigned Idx = getOrCreateVReg(*U.getOperand(2)); 1023 MIRBuilder.buildInsertVectorElement(Res, Val, Elt, Idx); 1024 return true; 1025 } 1026 1027 bool IRTranslator::translateExtractElement(const User &U, 1028 MachineIRBuilder &MIRBuilder) { 1029 // If it is a <1 x Ty> vector, use the scalar as it is 1030 // not a legal vector type in LLT. 1031 if (U.getOperand(0)->getType()->getVectorNumElements() == 1) { 1032 unsigned Elt = getOrCreateVReg(*U.getOperand(0)); 1033 ValToVReg[&U] = Elt; 1034 return true; 1035 } 1036 unsigned Res = getOrCreateVReg(U); 1037 unsigned Val = getOrCreateVReg(*U.getOperand(0)); 1038 unsigned Idx = getOrCreateVReg(*U.getOperand(1)); 1039 MIRBuilder.buildExtractVectorElement(Res, Val, Idx); 1040 return true; 1041 } 1042 1043 bool IRTranslator::translateShuffleVector(const User &U, 1044 MachineIRBuilder &MIRBuilder) { 1045 MIRBuilder.buildInstr(TargetOpcode::G_SHUFFLE_VECTOR) 1046 .addDef(getOrCreateVReg(U)) 1047 .addUse(getOrCreateVReg(*U.getOperand(0))) 1048 .addUse(getOrCreateVReg(*U.getOperand(1))) 1049 .addUse(getOrCreateVReg(*U.getOperand(2))); 1050 return true; 1051 } 1052 1053 bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) { 1054 const PHINode &PI = cast<PHINode>(U); 1055 auto MIB = MIRBuilder.buildInstr(TargetOpcode::PHI); 1056 MIB.addDef(getOrCreateVReg(PI)); 1057 1058 PendingPHIs.emplace_back(&PI, MIB.getInstr()); 1059 return true; 1060 } 1061 1062 void IRTranslator::finishPendingPhis() { 1063 for (std::pair<const PHINode *, MachineInstr *> &Phi : PendingPHIs) { 1064 const PHINode *PI = Phi.first; 1065 MachineInstrBuilder MIB(*MF, Phi.second); 1066 1067 // All MachineBasicBlocks exist, add them to the PHI. We assume IRTranslator 1068 // won't create extra control flow here, otherwise we need to find the 1069 // dominating predecessor here (or perhaps force the weirder IRTranslators 1070 // to provide a simple boundary). 1071 SmallSet<const BasicBlock *, 4> HandledPreds; 1072 1073 for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) { 1074 auto IRPred = PI->getIncomingBlock(i); 1075 if (HandledPreds.count(IRPred)) 1076 continue; 1077 1078 HandledPreds.insert(IRPred); 1079 unsigned ValReg = getOrCreateVReg(*PI->getIncomingValue(i)); 1080 for (auto Pred : getMachinePredBBs({IRPred, PI->getParent()})) { 1081 assert(Pred->isSuccessor(MIB->getParent()) && 1082 "incorrect CFG at MachineBasicBlock level"); 1083 MIB.addUse(ValReg); 1084 MIB.addMBB(Pred); 1085 } 1086 } 1087 } 1088 } 1089 1090 bool IRTranslator::translate(const Instruction &Inst) { 1091 CurBuilder.setDebugLoc(Inst.getDebugLoc()); 1092 switch(Inst.getOpcode()) { 1093 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1094 case Instruction::OPCODE: return translate##OPCODE(Inst, CurBuilder); 1095 #include "llvm/IR/Instruction.def" 1096 default: 1097 return false; 1098 } 1099 } 1100 1101 bool IRTranslator::translate(const Constant &C, unsigned Reg) { 1102 if (auto CI = dyn_cast<ConstantInt>(&C)) 1103 EntryBuilder.buildConstant(Reg, *CI); 1104 else if (auto CF = dyn_cast<ConstantFP>(&C)) 1105 EntryBuilder.buildFConstant(Reg, *CF); 1106 else if (isa<UndefValue>(C)) 1107 EntryBuilder.buildUndef(Reg); 1108 else if (isa<ConstantPointerNull>(C)) 1109 EntryBuilder.buildConstant(Reg, 0); 1110 else if (auto GV = dyn_cast<GlobalValue>(&C)) 1111 EntryBuilder.buildGlobalValue(Reg, GV); 1112 else if (auto CAZ = dyn_cast<ConstantAggregateZero>(&C)) { 1113 if (!CAZ->getType()->isVectorTy()) 1114 return false; 1115 // Return the scalar if it is a <1 x Ty> vector. 1116 if (CAZ->getNumElements() == 1) 1117 return translate(*CAZ->getElementValue(0u), Reg); 1118 std::vector<unsigned> Ops; 1119 for (unsigned i = 0; i < CAZ->getNumElements(); ++i) { 1120 Constant &Elt = *CAZ->getElementValue(i); 1121 Ops.push_back(getOrCreateVReg(Elt)); 1122 } 1123 EntryBuilder.buildMerge(Reg, Ops); 1124 } else if (auto CV = dyn_cast<ConstantDataVector>(&C)) { 1125 // Return the scalar if it is a <1 x Ty> vector. 1126 if (CV->getNumElements() == 1) 1127 return translate(*CV->getElementAsConstant(0), Reg); 1128 std::vector<unsigned> Ops; 1129 for (unsigned i = 0; i < CV->getNumElements(); ++i) { 1130 Constant &Elt = *CV->getElementAsConstant(i); 1131 Ops.push_back(getOrCreateVReg(Elt)); 1132 } 1133 EntryBuilder.buildMerge(Reg, Ops); 1134 } else if (auto CE = dyn_cast<ConstantExpr>(&C)) { 1135 switch(CE->getOpcode()) { 1136 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1137 case Instruction::OPCODE: return translate##OPCODE(*CE, EntryBuilder); 1138 #include "llvm/IR/Instruction.def" 1139 default: 1140 return false; 1141 } 1142 } else if (auto CS = dyn_cast<ConstantStruct>(&C)) { 1143 // Return the element if it is a single element ConstantStruct. 1144 if (CS->getNumOperands() == 1) { 1145 unsigned EltReg = getOrCreateVReg(*CS->getOperand(0)); 1146 EntryBuilder.buildCast(Reg, EltReg); 1147 return true; 1148 } 1149 SmallVector<unsigned, 4> Ops; 1150 SmallVector<uint64_t, 4> Indices; 1151 uint64_t Offset = 0; 1152 for (unsigned i = 0; i < CS->getNumOperands(); ++i) { 1153 unsigned OpReg = getOrCreateVReg(*CS->getOperand(i)); 1154 Ops.push_back(OpReg); 1155 Indices.push_back(Offset); 1156 Offset += MRI->getType(OpReg).getSizeInBits(); 1157 } 1158 EntryBuilder.buildSequence(Reg, Ops, Indices); 1159 } else if (auto CV = dyn_cast<ConstantVector>(&C)) { 1160 if (CV->getNumOperands() == 1) 1161 return translate(*CV->getOperand(0), Reg); 1162 SmallVector<unsigned, 4> Ops; 1163 for (unsigned i = 0; i < CV->getNumOperands(); ++i) { 1164 Ops.push_back(getOrCreateVReg(*CV->getOperand(i))); 1165 } 1166 EntryBuilder.buildMerge(Reg, Ops); 1167 } else 1168 return false; 1169 1170 return true; 1171 } 1172 1173 void IRTranslator::finalizeFunction() { 1174 // Release the memory used by the different maps we 1175 // needed during the translation. 1176 PendingPHIs.clear(); 1177 ValToVReg.clear(); 1178 FrameIndices.clear(); 1179 MachinePreds.clear(); 1180 // MachineIRBuilder::DebugLoc can outlive the DILocation it holds. Clear it 1181 // to avoid accessing free’d memory (in runOnMachineFunction) and to avoid 1182 // destroying it twice (in ~IRTranslator() and ~LLVMContext()) 1183 EntryBuilder = MachineIRBuilder(); 1184 CurBuilder = MachineIRBuilder(); 1185 } 1186 1187 bool IRTranslator::runOnMachineFunction(MachineFunction &CurMF) { 1188 MF = &CurMF; 1189 const Function &F = *MF->getFunction(); 1190 if (F.empty()) 1191 return false; 1192 CLI = MF->getSubtarget().getCallLowering(); 1193 CurBuilder.setMF(*MF); 1194 EntryBuilder.setMF(*MF); 1195 MRI = &MF->getRegInfo(); 1196 DL = &F.getParent()->getDataLayout(); 1197 TPC = &getAnalysis<TargetPassConfig>(); 1198 ORE = make_unique<OptimizationRemarkEmitter>(&F); 1199 1200 assert(PendingPHIs.empty() && "stale PHIs"); 1201 1202 // Release the per-function state when we return, whether we succeeded or not. 1203 auto FinalizeOnReturn = make_scope_exit([this]() { finalizeFunction(); }); 1204 1205 // Setup a separate basic-block for the arguments and constants 1206 MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock(); 1207 MF->push_back(EntryBB); 1208 EntryBuilder.setMBB(*EntryBB); 1209 1210 // Create all blocks, in IR order, to preserve the layout. 1211 for (const BasicBlock &BB: F) { 1212 auto *&MBB = BBToMBB[&BB]; 1213 1214 MBB = MF->CreateMachineBasicBlock(&BB); 1215 MF->push_back(MBB); 1216 1217 if (BB.hasAddressTaken()) 1218 MBB->setHasAddressTaken(); 1219 } 1220 1221 // Make our arguments/constants entry block fallthrough to the IR entry block. 1222 EntryBB->addSuccessor(&getMBB(F.front())); 1223 1224 // Lower the actual args into this basic block. 1225 SmallVector<unsigned, 8> VRegArgs; 1226 for (const Argument &Arg: F.args()) 1227 VRegArgs.push_back(getOrCreateVReg(Arg)); 1228 if (!CLI->lowerFormalArguments(EntryBuilder, F, VRegArgs)) { 1229 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure", 1230 MF->getFunction()->getSubprogram(), 1231 &MF->getFunction()->getEntryBlock()); 1232 R << "unable to lower arguments: " << ore::NV("Prototype", F.getType()); 1233 reportTranslationError(*MF, *TPC, *ORE, R); 1234 return false; 1235 } 1236 1237 // And translate the function! 1238 for (const BasicBlock &BB: F) { 1239 MachineBasicBlock &MBB = getMBB(BB); 1240 // Set the insertion point of all the following translations to 1241 // the end of this basic block. 1242 CurBuilder.setMBB(MBB); 1243 1244 for (const Instruction &Inst: BB) { 1245 if (translate(Inst)) 1246 continue; 1247 1248 std::string InstStrStorage; 1249 raw_string_ostream InstStr(InstStrStorage); 1250 InstStr << Inst; 1251 1252 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure", 1253 Inst.getDebugLoc(), &BB); 1254 R << "unable to translate instruction: " << ore::NV("Opcode", &Inst) 1255 << ": '" << InstStr.str() << "'"; 1256 reportTranslationError(*MF, *TPC, *ORE, R); 1257 return false; 1258 } 1259 } 1260 1261 finishPendingPhis(); 1262 1263 // Merge the argument lowering and constants block with its single 1264 // successor, the LLVM-IR entry block. We want the basic block to 1265 // be maximal. 1266 assert(EntryBB->succ_size() == 1 && 1267 "Custom BB used for lowering should have only one successor"); 1268 // Get the successor of the current entry block. 1269 MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin(); 1270 assert(NewEntryBB.pred_size() == 1 && 1271 "LLVM-IR entry block has a predecessor!?"); 1272 // Move all the instruction from the current entry block to the 1273 // new entry block. 1274 NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(), 1275 EntryBB->end()); 1276 1277 // Update the live-in information for the new entry block. 1278 for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins()) 1279 NewEntryBB.addLiveIn(LiveIn); 1280 NewEntryBB.sortUniqueLiveIns(); 1281 1282 // Get rid of the now empty basic block. 1283 EntryBB->removeSuccessor(&NewEntryBB); 1284 MF->remove(EntryBB); 1285 MF->DeleteMachineBasicBlock(EntryBB); 1286 1287 assert(&MF->front() == &NewEntryBB && 1288 "New entry wasn't next in the list of basic block!"); 1289 1290 return false; 1291 } 1292