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/SmallVector.h" 16 #include "llvm/CodeGen/GlobalISel/CallLowering.h" 17 #include "llvm/CodeGen/Analysis.h" 18 #include "llvm/CodeGen/MachineFunction.h" 19 #include "llvm/CodeGen/MachineFrameInfo.h" 20 #include "llvm/CodeGen/MachineModuleInfo.h" 21 #include "llvm/CodeGen/MachineRegisterInfo.h" 22 #include "llvm/CodeGen/TargetPassConfig.h" 23 #include "llvm/IR/Constant.h" 24 #include "llvm/IR/Function.h" 25 #include "llvm/IR/GetElementPtrTypeIterator.h" 26 #include "llvm/IR/IntrinsicInst.h" 27 #include "llvm/IR/Type.h" 28 #include "llvm/IR/Value.h" 29 #include "llvm/Target/TargetIntrinsicInfo.h" 30 #include "llvm/Target/TargetLowering.h" 31 32 #define DEBUG_TYPE "irtranslator" 33 34 using namespace llvm; 35 36 char IRTranslator::ID = 0; 37 INITIALIZE_PASS_BEGIN(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI", 38 false, false) 39 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig) 40 INITIALIZE_PASS_END(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI", 41 false, false) 42 43 static void reportTranslationError(const Value &V, const Twine &Message) { 44 std::string ErrStorage; 45 raw_string_ostream Err(ErrStorage); 46 Err << Message << ": " << V << '\n'; 47 report_fatal_error(Err.str()); 48 } 49 50 IRTranslator::IRTranslator() : MachineFunctionPass(ID), MRI(nullptr) { 51 initializeIRTranslatorPass(*PassRegistry::getPassRegistry()); 52 } 53 54 void IRTranslator::getAnalysisUsage(AnalysisUsage &AU) const { 55 AU.addRequired<TargetPassConfig>(); 56 MachineFunctionPass::getAnalysisUsage(AU); 57 } 58 59 60 unsigned IRTranslator::getOrCreateVReg(const Value &Val) { 61 unsigned &ValReg = ValToVReg[&Val]; 62 // Check if this is the first time we see Val. 63 if (!ValReg) { 64 // Fill ValRegsSequence with the sequence of registers 65 // we need to concat together to produce the value. 66 assert(Val.getType()->isSized() && 67 "Don't know how to create an empty vreg"); 68 unsigned VReg = MRI->createGenericVirtualRegister(LLT{*Val.getType(), *DL}); 69 ValReg = VReg; 70 71 if (auto CV = dyn_cast<Constant>(&Val)) { 72 bool Success = translate(*CV, VReg); 73 if (!Success) { 74 if (!TPC->isGlobalISelAbortEnabled()) { 75 MF->getProperties().set( 76 MachineFunctionProperties::Property::FailedISel); 77 return VReg; 78 } 79 reportTranslationError(Val, "unable to translate constant"); 80 } 81 } 82 } 83 return ValReg; 84 } 85 86 int IRTranslator::getOrCreateFrameIndex(const AllocaInst &AI) { 87 if (FrameIndices.find(&AI) != FrameIndices.end()) 88 return FrameIndices[&AI]; 89 90 unsigned ElementSize = DL->getTypeStoreSize(AI.getAllocatedType()); 91 unsigned Size = 92 ElementSize * cast<ConstantInt>(AI.getArraySize())->getZExtValue(); 93 94 // Always allocate at least one byte. 95 Size = std::max(Size, 1u); 96 97 unsigned Alignment = AI.getAlignment(); 98 if (!Alignment) 99 Alignment = DL->getABITypeAlignment(AI.getAllocatedType()); 100 101 int &FI = FrameIndices[&AI]; 102 FI = MF->getFrameInfo().CreateStackObject(Size, Alignment, false, &AI); 103 return FI; 104 } 105 106 unsigned IRTranslator::getMemOpAlignment(const Instruction &I) { 107 unsigned Alignment = 0; 108 Type *ValTy = nullptr; 109 if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) { 110 Alignment = SI->getAlignment(); 111 ValTy = SI->getValueOperand()->getType(); 112 } else if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) { 113 Alignment = LI->getAlignment(); 114 ValTy = LI->getType(); 115 } else if (!TPC->isGlobalISelAbortEnabled()) { 116 MF->getProperties().set( 117 MachineFunctionProperties::Property::FailedISel); 118 return 1; 119 } else 120 llvm_unreachable("unhandled memory instruction"); 121 122 return Alignment ? Alignment : DL->getABITypeAlignment(ValTy); 123 } 124 125 MachineBasicBlock &IRTranslator::getOrCreateBB(const BasicBlock &BB) { 126 MachineBasicBlock *&MBB = BBToMBB[&BB]; 127 if (!MBB) { 128 MBB = MF->CreateMachineBasicBlock(); 129 MF->push_back(MBB); 130 } 131 return *MBB; 132 } 133 134 bool IRTranslator::translateBinaryOp(unsigned Opcode, const User &U, 135 MachineIRBuilder &MIRBuilder) { 136 // FIXME: handle signed/unsigned wrapping flags. 137 138 // Get or create a virtual register for each value. 139 // Unless the value is a Constant => loadimm cst? 140 // or inline constant each time? 141 // Creation of a virtual register needs to have a size. 142 unsigned Op0 = getOrCreateVReg(*U.getOperand(0)); 143 unsigned Op1 = getOrCreateVReg(*U.getOperand(1)); 144 unsigned Res = getOrCreateVReg(U); 145 MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op0).addUse(Op1); 146 return true; 147 } 148 149 bool IRTranslator::translateCompare(const User &U, 150 MachineIRBuilder &MIRBuilder) { 151 const CmpInst *CI = dyn_cast<CmpInst>(&U); 152 unsigned Op0 = getOrCreateVReg(*U.getOperand(0)); 153 unsigned Op1 = getOrCreateVReg(*U.getOperand(1)); 154 unsigned Res = getOrCreateVReg(U); 155 CmpInst::Predicate Pred = 156 CI ? CI->getPredicate() : static_cast<CmpInst::Predicate>( 157 cast<ConstantExpr>(U).getPredicate()); 158 159 if (CmpInst::isIntPredicate(Pred)) 160 MIRBuilder.buildICmp(Pred, Res, Op0, Op1); 161 else 162 MIRBuilder.buildFCmp(Pred, Res, Op0, Op1); 163 164 return true; 165 } 166 167 bool IRTranslator::translateRet(const User &U, MachineIRBuilder &MIRBuilder) { 168 const ReturnInst &RI = cast<ReturnInst>(U); 169 const Value *Ret = RI.getReturnValue(); 170 // The target may mess up with the insertion point, but 171 // this is not important as a return is the last instruction 172 // of the block anyway. 173 return CLI->lowerReturn(MIRBuilder, Ret, !Ret ? 0 : getOrCreateVReg(*Ret)); 174 } 175 176 bool IRTranslator::translateBr(const User &U, MachineIRBuilder &MIRBuilder) { 177 const BranchInst &BrInst = cast<BranchInst>(U); 178 unsigned Succ = 0; 179 if (!BrInst.isUnconditional()) { 180 // We want a G_BRCOND to the true BB followed by an unconditional branch. 181 unsigned Tst = getOrCreateVReg(*BrInst.getCondition()); 182 const BasicBlock &TrueTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ++)); 183 MachineBasicBlock &TrueBB = getOrCreateBB(TrueTgt); 184 MIRBuilder.buildBrCond(Tst, TrueBB); 185 } 186 187 const BasicBlock &BrTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ)); 188 MachineBasicBlock &TgtBB = getOrCreateBB(BrTgt); 189 MIRBuilder.buildBr(TgtBB); 190 191 // Link successors. 192 MachineBasicBlock &CurBB = MIRBuilder.getMBB(); 193 for (const BasicBlock *Succ : BrInst.successors()) 194 CurBB.addSuccessor(&getOrCreateBB(*Succ)); 195 return true; 196 } 197 198 bool IRTranslator::translateLoad(const User &U, MachineIRBuilder &MIRBuilder) { 199 const LoadInst &LI = cast<LoadInst>(U); 200 201 if (!TPC->isGlobalISelAbortEnabled() && LI.isAtomic()) 202 return false; 203 204 assert(!LI.isAtomic() && "only non-atomic loads are supported at the moment"); 205 auto Flags = LI.isVolatile() ? MachineMemOperand::MOVolatile 206 : MachineMemOperand::MONone; 207 Flags |= MachineMemOperand::MOLoad; 208 209 unsigned Res = getOrCreateVReg(LI); 210 unsigned Addr = getOrCreateVReg(*LI.getPointerOperand()); 211 LLT VTy{*LI.getType(), *DL}, PTy{*LI.getPointerOperand()->getType(), *DL}; 212 MIRBuilder.buildLoad( 213 Res, Addr, 214 *MF->getMachineMemOperand(MachinePointerInfo(LI.getPointerOperand()), 215 Flags, DL->getTypeStoreSize(LI.getType()), 216 getMemOpAlignment(LI))); 217 return true; 218 } 219 220 bool IRTranslator::translateStore(const User &U, MachineIRBuilder &MIRBuilder) { 221 const StoreInst &SI = cast<StoreInst>(U); 222 223 if (!TPC->isGlobalISelAbortEnabled() && SI.isAtomic()) 224 return false; 225 226 assert(!SI.isAtomic() && "only non-atomic stores supported at the moment"); 227 auto Flags = SI.isVolatile() ? MachineMemOperand::MOVolatile 228 : MachineMemOperand::MONone; 229 Flags |= MachineMemOperand::MOStore; 230 231 unsigned Val = getOrCreateVReg(*SI.getValueOperand()); 232 unsigned Addr = getOrCreateVReg(*SI.getPointerOperand()); 233 LLT VTy{*SI.getValueOperand()->getType(), *DL}, 234 PTy{*SI.getPointerOperand()->getType(), *DL}; 235 236 MIRBuilder.buildStore( 237 Val, Addr, 238 *MF->getMachineMemOperand( 239 MachinePointerInfo(SI.getPointerOperand()), Flags, 240 DL->getTypeStoreSize(SI.getValueOperand()->getType()), 241 getMemOpAlignment(SI))); 242 return true; 243 } 244 245 bool IRTranslator::translateExtractValue(const User &U, 246 MachineIRBuilder &MIRBuilder) { 247 const Value *Src = U.getOperand(0); 248 Type *Int32Ty = Type::getInt32Ty(U.getContext()); 249 SmallVector<Value *, 1> Indices; 250 251 // getIndexedOffsetInType is designed for GEPs, so the first index is the 252 // usual array element rather than looking into the actual aggregate. 253 Indices.push_back(ConstantInt::get(Int32Ty, 0)); 254 255 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) { 256 for (auto Idx : EVI->indices()) 257 Indices.push_back(ConstantInt::get(Int32Ty, Idx)); 258 } else { 259 for (unsigned i = 1; i < U.getNumOperands(); ++i) 260 Indices.push_back(U.getOperand(i)); 261 } 262 263 uint64_t Offset = 8 * DL->getIndexedOffsetInType(Src->getType(), Indices); 264 265 unsigned Res = getOrCreateVReg(U); 266 MIRBuilder.buildExtract(Res, Offset, getOrCreateVReg(*Src)); 267 268 return true; 269 } 270 271 bool IRTranslator::translateInsertValue(const User &U, 272 MachineIRBuilder &MIRBuilder) { 273 const Value *Src = U.getOperand(0); 274 Type *Int32Ty = Type::getInt32Ty(U.getContext()); 275 SmallVector<Value *, 1> Indices; 276 277 // getIndexedOffsetInType is designed for GEPs, so the first index is the 278 // usual array element rather than looking into the actual aggregate. 279 Indices.push_back(ConstantInt::get(Int32Ty, 0)); 280 281 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) { 282 for (auto Idx : IVI->indices()) 283 Indices.push_back(ConstantInt::get(Int32Ty, Idx)); 284 } else { 285 for (unsigned i = 2; i < U.getNumOperands(); ++i) 286 Indices.push_back(U.getOperand(i)); 287 } 288 289 uint64_t Offset = 8 * DL->getIndexedOffsetInType(Src->getType(), Indices); 290 291 unsigned Res = getOrCreateVReg(U); 292 const Value &Inserted = *U.getOperand(1); 293 MIRBuilder.buildInsert(Res, getOrCreateVReg(*Src), getOrCreateVReg(Inserted), 294 Offset); 295 296 return true; 297 } 298 299 bool IRTranslator::translateSelect(const User &U, 300 MachineIRBuilder &MIRBuilder) { 301 MIRBuilder.buildSelect(getOrCreateVReg(U), getOrCreateVReg(*U.getOperand(0)), 302 getOrCreateVReg(*U.getOperand(1)), 303 getOrCreateVReg(*U.getOperand(2))); 304 return true; 305 } 306 307 bool IRTranslator::translateBitCast(const User &U, 308 MachineIRBuilder &MIRBuilder) { 309 if (LLT{*U.getOperand(0)->getType(), *DL} == LLT{*U.getType(), *DL}) { 310 unsigned &Reg = ValToVReg[&U]; 311 if (Reg) 312 MIRBuilder.buildCopy(Reg, getOrCreateVReg(*U.getOperand(0))); 313 else 314 Reg = getOrCreateVReg(*U.getOperand(0)); 315 return true; 316 } 317 return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder); 318 } 319 320 bool IRTranslator::translateCast(unsigned Opcode, const User &U, 321 MachineIRBuilder &MIRBuilder) { 322 unsigned Op = getOrCreateVReg(*U.getOperand(0)); 323 unsigned Res = getOrCreateVReg(U); 324 MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op); 325 return true; 326 } 327 328 bool IRTranslator::translateGetElementPtr(const User &U, 329 MachineIRBuilder &MIRBuilder) { 330 // FIXME: support vector GEPs. 331 if (U.getType()->isVectorTy()) 332 return false; 333 334 Value &Op0 = *U.getOperand(0); 335 unsigned BaseReg = getOrCreateVReg(Op0); 336 LLT PtrTy{*Op0.getType(), *DL}; 337 unsigned PtrSize = DL->getPointerSizeInBits(PtrTy.getAddressSpace()); 338 LLT OffsetTy = LLT::scalar(PtrSize); 339 340 int64_t Offset = 0; 341 for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U); 342 GTI != E; ++GTI) { 343 const Value *Idx = GTI.getOperand(); 344 if (StructType *StTy = GTI.getStructTypeOrNull()) { 345 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 346 Offset += DL->getStructLayout(StTy)->getElementOffset(Field); 347 continue; 348 } else { 349 uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType()); 350 351 // If this is a scalar constant or a splat vector of constants, 352 // handle it quickly. 353 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) { 354 Offset += ElementSize * CI->getSExtValue(); 355 continue; 356 } 357 358 if (Offset != 0) { 359 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy); 360 unsigned OffsetReg = MRI->createGenericVirtualRegister(OffsetTy); 361 MIRBuilder.buildConstant(OffsetReg, Offset); 362 MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg); 363 364 BaseReg = NewBaseReg; 365 Offset = 0; 366 } 367 368 // N = N + Idx * ElementSize; 369 unsigned ElementSizeReg = MRI->createGenericVirtualRegister(OffsetTy); 370 MIRBuilder.buildConstant(ElementSizeReg, ElementSize); 371 372 unsigned IdxReg = getOrCreateVReg(*Idx); 373 if (MRI->getType(IdxReg) != OffsetTy) { 374 unsigned NewIdxReg = MRI->createGenericVirtualRegister(OffsetTy); 375 MIRBuilder.buildSExtOrTrunc(NewIdxReg, IdxReg); 376 IdxReg = NewIdxReg; 377 } 378 379 unsigned OffsetReg = MRI->createGenericVirtualRegister(OffsetTy); 380 MIRBuilder.buildMul(OffsetReg, ElementSizeReg, IdxReg); 381 382 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy); 383 MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg); 384 BaseReg = NewBaseReg; 385 } 386 } 387 388 if (Offset != 0) { 389 unsigned OffsetReg = MRI->createGenericVirtualRegister(OffsetTy); 390 MIRBuilder.buildConstant(OffsetReg, Offset); 391 MIRBuilder.buildGEP(getOrCreateVReg(U), BaseReg, OffsetReg); 392 return true; 393 } 394 395 MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg); 396 return true; 397 } 398 399 bool IRTranslator::translateMemcpy(const CallInst &CI, 400 MachineIRBuilder &MIRBuilder) { 401 LLT SizeTy{*CI.getArgOperand(2)->getType(), *DL}; 402 if (cast<PointerType>(CI.getArgOperand(0)->getType())->getAddressSpace() != 403 0 || 404 cast<PointerType>(CI.getArgOperand(1)->getType())->getAddressSpace() != 405 0 || 406 SizeTy.getSizeInBits() != DL->getPointerSizeInBits(0)) 407 return false; 408 409 SmallVector<CallLowering::ArgInfo, 8> Args; 410 for (int i = 0; i < 3; ++i) { 411 const auto &Arg = CI.getArgOperand(i); 412 Args.emplace_back(getOrCreateVReg(*Arg), Arg->getType()); 413 } 414 415 MachineOperand Callee = MachineOperand::CreateES("memcpy"); 416 417 return CLI->lowerCall(MIRBuilder, Callee, 418 CallLowering::ArgInfo(0, CI.getType()), Args); 419 } 420 421 void IRTranslator::getStackGuard(unsigned DstReg, 422 MachineIRBuilder &MIRBuilder) { 423 auto MIB = MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD); 424 MIB.addDef(DstReg); 425 426 auto &TLI = *MF->getSubtarget().getTargetLowering(); 427 Value *Global = TLI.getSDagStackGuard(*MF->getFunction()->getParent()); 428 if (!Global) 429 return; 430 431 MachinePointerInfo MPInfo(Global); 432 MachineInstr::mmo_iterator MemRefs = MF->allocateMemRefsArray(1); 433 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 434 MachineMemOperand::MODereferenceable; 435 *MemRefs = 436 MF->getMachineMemOperand(MPInfo, Flags, DL->getPointerSizeInBits() / 8, 437 DL->getPointerABIAlignment()); 438 MIB.setMemRefs(MemRefs, MemRefs + 1); 439 } 440 441 bool IRTranslator::translateOverflowIntrinsic(const CallInst &CI, unsigned Op, 442 MachineIRBuilder &MIRBuilder) { 443 LLT Ty{*CI.getOperand(0)->getType(), *DL}; 444 LLT s1 = LLT::scalar(1); 445 unsigned Width = Ty.getSizeInBits(); 446 unsigned Res = MRI->createGenericVirtualRegister(Ty); 447 unsigned Overflow = MRI->createGenericVirtualRegister(s1); 448 auto MIB = MIRBuilder.buildInstr(Op) 449 .addDef(Res) 450 .addDef(Overflow) 451 .addUse(getOrCreateVReg(*CI.getOperand(0))) 452 .addUse(getOrCreateVReg(*CI.getOperand(1))); 453 454 if (Op == TargetOpcode::G_UADDE || Op == TargetOpcode::G_USUBE) { 455 unsigned Zero = MRI->createGenericVirtualRegister(s1); 456 EntryBuilder.buildConstant(Zero, 0); 457 MIB.addUse(Zero); 458 } 459 460 MIRBuilder.buildSequence(getOrCreateVReg(CI), Res, 0, Overflow, Width); 461 return true; 462 } 463 464 bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID, 465 MachineIRBuilder &MIRBuilder) { 466 switch (ID) { 467 default: 468 break; 469 case Intrinsic::dbg_declare: 470 case Intrinsic::dbg_value: 471 // FIXME: these obviously need to be supported properly. 472 MF->getProperties().set( 473 MachineFunctionProperties::Property::FailedISel); 474 return true; 475 case Intrinsic::uadd_with_overflow: 476 return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDE, MIRBuilder); 477 case Intrinsic::sadd_with_overflow: 478 return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder); 479 case Intrinsic::usub_with_overflow: 480 return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBE, MIRBuilder); 481 case Intrinsic::ssub_with_overflow: 482 return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder); 483 case Intrinsic::umul_with_overflow: 484 return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder); 485 case Intrinsic::smul_with_overflow: 486 return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder); 487 case Intrinsic::memcpy: 488 return translateMemcpy(CI, MIRBuilder); 489 case Intrinsic::eh_typeid_for: { 490 GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0)); 491 unsigned Reg = getOrCreateVReg(CI); 492 unsigned TypeID = MF->getTypeIDFor(GV); 493 MIRBuilder.buildConstant(Reg, TypeID); 494 return true; 495 } 496 case Intrinsic::objectsize: { 497 // If we don't know by now, we're never going to know. 498 const ConstantInt *Min = cast<ConstantInt>(CI.getArgOperand(1)); 499 500 MIRBuilder.buildConstant(getOrCreateVReg(CI), Min->isZero() ? -1ULL : 0); 501 return true; 502 } 503 case Intrinsic::stackguard: 504 getStackGuard(getOrCreateVReg(CI), MIRBuilder); 505 return true; 506 case Intrinsic::stackprotector: { 507 LLT PtrTy{*CI.getArgOperand(0)->getType(), *DL}; 508 unsigned GuardVal = MRI->createGenericVirtualRegister(PtrTy); 509 getStackGuard(GuardVal, MIRBuilder); 510 511 AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1)); 512 MIRBuilder.buildStore( 513 GuardVal, getOrCreateVReg(*Slot), 514 *MF->getMachineMemOperand( 515 MachinePointerInfo::getFixedStack(*MF, 516 getOrCreateFrameIndex(*Slot)), 517 MachineMemOperand::MOStore | MachineMemOperand::MOVolatile, 518 PtrTy.getSizeInBits() / 8, 8)); 519 return true; 520 } 521 } 522 return false; 523 } 524 525 bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) { 526 const CallInst &CI = cast<CallInst>(U); 527 auto TII = MF->getTarget().getIntrinsicInfo(); 528 const Function *F = CI.getCalledFunction(); 529 530 if (!F || !F->isIntrinsic()) { 531 unsigned Res = CI.getType()->isVoidTy() ? 0 : getOrCreateVReg(CI); 532 SmallVector<unsigned, 8> Args; 533 for (auto &Arg: CI.arg_operands()) 534 Args.push_back(getOrCreateVReg(*Arg)); 535 536 return CLI->lowerCall(MIRBuilder, CI, Res, Args, [&]() { 537 return getOrCreateVReg(*CI.getCalledValue()); 538 }); 539 } 540 541 Intrinsic::ID ID = F->getIntrinsicID(); 542 if (TII && ID == Intrinsic::not_intrinsic) 543 ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F)); 544 545 assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic"); 546 547 if (translateKnownIntrinsic(CI, ID, MIRBuilder)) 548 return true; 549 550 unsigned Res = CI.getType()->isVoidTy() ? 0 : getOrCreateVReg(CI); 551 MachineInstrBuilder MIB = 552 MIRBuilder.buildIntrinsic(ID, Res, !CI.doesNotAccessMemory()); 553 554 for (auto &Arg : CI.arg_operands()) { 555 if (ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) 556 MIB.addImm(CI->getSExtValue()); 557 else 558 MIB.addUse(getOrCreateVReg(*Arg)); 559 } 560 return true; 561 } 562 563 bool IRTranslator::translateInvoke(const User &U, 564 MachineIRBuilder &MIRBuilder) { 565 const InvokeInst &I = cast<InvokeInst>(U); 566 MCContext &Context = MF->getContext(); 567 568 const BasicBlock *ReturnBB = I.getSuccessor(0); 569 const BasicBlock *EHPadBB = I.getSuccessor(1); 570 571 const Value *Callee(I.getCalledValue()); 572 const Function *Fn = dyn_cast<Function>(Callee); 573 if (isa<InlineAsm>(Callee)) 574 return false; 575 576 // FIXME: support invoking patchpoint and statepoint intrinsics. 577 if (Fn && Fn->isIntrinsic()) 578 return false; 579 580 // FIXME: support whatever these are. 581 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 582 return false; 583 584 // FIXME: support Windows exception handling. 585 if (!isa<LandingPadInst>(EHPadBB->front())) 586 return false; 587 588 589 // Emit the actual call, bracketed by EH_LABELs so that the MF knows about 590 // the region covered by the try. 591 MCSymbol *BeginSymbol = Context.createTempSymbol(); 592 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol); 593 594 unsigned Res = I.getType()->isVoidTy() ? 0 : getOrCreateVReg(I); 595 SmallVector<CallLowering::ArgInfo, 8> Args; 596 for (auto &Arg: I.arg_operands()) 597 Args.emplace_back(getOrCreateVReg(*Arg), Arg->getType()); 598 599 if (!CLI->lowerCall(MIRBuilder, MachineOperand::CreateGA(Fn, 0), 600 CallLowering::ArgInfo(Res, I.getType()), Args)) 601 return false; 602 603 MCSymbol *EndSymbol = Context.createTempSymbol(); 604 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol); 605 606 // FIXME: track probabilities. 607 MachineBasicBlock &EHPadMBB = getOrCreateBB(*EHPadBB), 608 &ReturnMBB = getOrCreateBB(*ReturnBB); 609 MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol); 610 MIRBuilder.getMBB().addSuccessor(&ReturnMBB); 611 MIRBuilder.getMBB().addSuccessor(&EHPadMBB); 612 613 return true; 614 } 615 616 bool IRTranslator::translateLandingPad(const User &U, 617 MachineIRBuilder &MIRBuilder) { 618 const LandingPadInst &LP = cast<LandingPadInst>(U); 619 620 MachineBasicBlock &MBB = MIRBuilder.getMBB(); 621 addLandingPadInfo(LP, MBB); 622 623 MBB.setIsEHPad(); 624 625 // If there aren't registers to copy the values into (e.g., during SjLj 626 // exceptions), then don't bother. 627 auto &TLI = *MF->getSubtarget().getTargetLowering(); 628 const Constant *PersonalityFn = MF->getFunction()->getPersonalityFn(); 629 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 630 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 631 return true; 632 633 // If landingpad's return type is token type, we don't create DAG nodes 634 // for its exception pointer and selector value. The extraction of exception 635 // pointer or selector value from token type landingpads is not currently 636 // supported. 637 if (LP.getType()->isTokenTy()) 638 return true; 639 640 // Add a label to mark the beginning of the landing pad. Deletion of the 641 // landing pad can thus be detected via the MachineModuleInfo. 642 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL) 643 .addSym(MF->addLandingPad(&MBB)); 644 645 // Mark exception register as live in. 646 SmallVector<unsigned, 2> Regs; 647 SmallVector<uint64_t, 2> Offsets; 648 LLT p0 = LLT::pointer(0, DL->getPointerSizeInBits()); 649 if (unsigned Reg = TLI.getExceptionPointerRegister(PersonalityFn)) { 650 unsigned VReg = MRI->createGenericVirtualRegister(p0); 651 MIRBuilder.buildCopy(VReg, Reg); 652 Regs.push_back(VReg); 653 Offsets.push_back(0); 654 } 655 656 if (unsigned Reg = TLI.getExceptionSelectorRegister(PersonalityFn)) { 657 unsigned VReg = MRI->createGenericVirtualRegister(p0); 658 MIRBuilder.buildCopy(VReg, Reg); 659 Regs.push_back(VReg); 660 Offsets.push_back(p0.getSizeInBits()); 661 } 662 663 MIRBuilder.buildSequence(getOrCreateVReg(LP), Regs, Offsets); 664 return true; 665 } 666 667 bool IRTranslator::translateStaticAlloca(const AllocaInst &AI, 668 MachineIRBuilder &MIRBuilder) { 669 if (!TPC->isGlobalISelAbortEnabled() && !AI.isStaticAlloca()) 670 return false; 671 672 assert(AI.isStaticAlloca() && "only handle static allocas now"); 673 unsigned Res = getOrCreateVReg(AI); 674 int FI = getOrCreateFrameIndex(AI); 675 MIRBuilder.buildFrameIndex(Res, FI); 676 return true; 677 } 678 679 bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) { 680 const PHINode &PI = cast<PHINode>(U); 681 auto MIB = MIRBuilder.buildInstr(TargetOpcode::PHI); 682 MIB.addDef(getOrCreateVReg(PI)); 683 684 PendingPHIs.emplace_back(&PI, MIB.getInstr()); 685 return true; 686 } 687 688 void IRTranslator::finishPendingPhis() { 689 for (std::pair<const PHINode *, MachineInstr *> &Phi : PendingPHIs) { 690 const PHINode *PI = Phi.first; 691 MachineInstrBuilder MIB(*MF, Phi.second); 692 693 // All MachineBasicBlocks exist, add them to the PHI. We assume IRTranslator 694 // won't create extra control flow here, otherwise we need to find the 695 // dominating predecessor here (or perhaps force the weirder IRTranslators 696 // to provide a simple boundary). 697 for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) { 698 assert(BBToMBB[PI->getIncomingBlock(i)]->isSuccessor(MIB->getParent()) && 699 "I appear to have misunderstood Machine PHIs"); 700 MIB.addUse(getOrCreateVReg(*PI->getIncomingValue(i))); 701 MIB.addMBB(BBToMBB[PI->getIncomingBlock(i)]); 702 } 703 } 704 } 705 706 bool IRTranslator::translate(const Instruction &Inst) { 707 CurBuilder.setDebugLoc(Inst.getDebugLoc()); 708 switch(Inst.getOpcode()) { 709 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 710 case Instruction::OPCODE: return translate##OPCODE(Inst, CurBuilder); 711 #include "llvm/IR/Instruction.def" 712 default: 713 if (!TPC->isGlobalISelAbortEnabled()) 714 return false; 715 llvm_unreachable("unknown opcode"); 716 } 717 } 718 719 bool IRTranslator::translate(const Constant &C, unsigned Reg) { 720 if (auto CI = dyn_cast<ConstantInt>(&C)) 721 EntryBuilder.buildConstant(Reg, *CI); 722 else if (auto CF = dyn_cast<ConstantFP>(&C)) 723 EntryBuilder.buildFConstant(Reg, *CF); 724 else if (isa<UndefValue>(C)) 725 EntryBuilder.buildInstr(TargetOpcode::IMPLICIT_DEF).addDef(Reg); 726 else if (isa<ConstantPointerNull>(C)) 727 EntryBuilder.buildConstant(Reg, 0); 728 else if (auto GV = dyn_cast<GlobalValue>(&C)) 729 EntryBuilder.buildGlobalValue(Reg, GV); 730 else if (auto CE = dyn_cast<ConstantExpr>(&C)) { 731 switch(CE->getOpcode()) { 732 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 733 case Instruction::OPCODE: return translate##OPCODE(*CE, EntryBuilder); 734 #include "llvm/IR/Instruction.def" 735 default: 736 if (!TPC->isGlobalISelAbortEnabled()) 737 return false; 738 llvm_unreachable("unknown opcode"); 739 } 740 } else if (!TPC->isGlobalISelAbortEnabled()) 741 return false; 742 else 743 llvm_unreachable("unhandled constant kind"); 744 745 return true; 746 } 747 748 void IRTranslator::finalizeFunction() { 749 // Release the memory used by the different maps we 750 // needed during the translation. 751 PendingPHIs.clear(); 752 ValToVReg.clear(); 753 FrameIndices.clear(); 754 Constants.clear(); 755 } 756 757 bool IRTranslator::runOnMachineFunction(MachineFunction &CurMF) { 758 MF = &CurMF; 759 const Function &F = *MF->getFunction(); 760 if (F.empty()) 761 return false; 762 CLI = MF->getSubtarget().getCallLowering(); 763 CurBuilder.setMF(*MF); 764 EntryBuilder.setMF(*MF); 765 MRI = &MF->getRegInfo(); 766 DL = &F.getParent()->getDataLayout(); 767 TPC = &getAnalysis<TargetPassConfig>(); 768 769 assert(PendingPHIs.empty() && "stale PHIs"); 770 771 // Setup a separate basic-block for the arguments and constants, falling 772 // through to the IR-level Function's entry block. 773 MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock(); 774 MF->push_back(EntryBB); 775 EntryBB->addSuccessor(&getOrCreateBB(F.front())); 776 EntryBuilder.setMBB(*EntryBB); 777 778 // Lower the actual args into this basic block. 779 SmallVector<unsigned, 8> VRegArgs; 780 for (const Argument &Arg: F.args()) 781 VRegArgs.push_back(getOrCreateVReg(Arg)); 782 bool Succeeded = CLI->lowerFormalArguments(EntryBuilder, F, VRegArgs); 783 if (!Succeeded) { 784 if (!TPC->isGlobalISelAbortEnabled()) { 785 MF->getProperties().set( 786 MachineFunctionProperties::Property::FailedISel); 787 finalizeFunction(); 788 return false; 789 } 790 report_fatal_error("Unable to lower arguments"); 791 } 792 793 // And translate the function! 794 for (const BasicBlock &BB: F) { 795 MachineBasicBlock &MBB = getOrCreateBB(BB); 796 // Set the insertion point of all the following translations to 797 // the end of this basic block. 798 CurBuilder.setMBB(MBB); 799 800 for (const Instruction &Inst: BB) { 801 Succeeded &= translate(Inst); 802 if (!Succeeded) { 803 if (TPC->isGlobalISelAbortEnabled()) 804 reportTranslationError(Inst, "unable to translate instruction"); 805 MF->getProperties().set( 806 MachineFunctionProperties::Property::FailedISel); 807 break; 808 } 809 } 810 } 811 812 if (Succeeded) { 813 finishPendingPhis(); 814 815 // Now that the MachineFrameInfo has been configured, no further changes to 816 // the reserved registers are possible. 817 MRI->freezeReservedRegs(*MF); 818 } 819 820 finalizeFunction(); 821 822 return false; 823 } 824