LLVM API Documentation

AutoUpgrade.cpp
Go to the documentation of this file.
00001 //===-- AutoUpgrade.cpp - Implement auto-upgrade helper functions ---------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the auto-upgrade helper functions
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/IR/AutoUpgrade.h"
00015 #include "llvm/IR/CFG.h"
00016 #include "llvm/IR/CallSite.h"
00017 #include "llvm/IR/Constants.h"
00018 #include "llvm/IR/DIBuilder.h"
00019 #include "llvm/IR/DebugInfo.h"
00020 #include "llvm/IR/DiagnosticInfo.h"
00021 #include "llvm/IR/Function.h"
00022 #include "llvm/IR/IRBuilder.h"
00023 #include "llvm/IR/Instruction.h"
00024 #include "llvm/IR/IntrinsicInst.h"
00025 #include "llvm/IR/LLVMContext.h"
00026 #include "llvm/IR/Module.h"
00027 #include "llvm/Support/ErrorHandling.h"
00028 #include <cstring>
00029 using namespace llvm;
00030 
00031 // Upgrade the declarations of the SSE4.1 functions whose arguments have
00032 // changed their type from v4f32 to v2i64.
00033 static bool UpgradeSSE41Function(Function* F, Intrinsic::ID IID,
00034                                  Function *&NewFn) {
00035   // Check whether this is an old version of the function, which received
00036   // v4f32 arguments.
00037   Type *Arg0Type = F->getFunctionType()->getParamType(0);
00038   if (Arg0Type != VectorType::get(Type::getFloatTy(F->getContext()), 4))
00039     return false;
00040 
00041   // Yes, it's old, replace it with new version.
00042   F->setName(F->getName() + ".old");
00043   NewFn = Intrinsic::getDeclaration(F->getParent(), IID);
00044   return true;
00045 }
00046 
00047 // Upgrade the declarations of intrinsic functions whose 8-bit immediate mask
00048 // arguments have changed their type from i32 to i8.
00049 static bool UpgradeX86IntrinsicsWith8BitMask(Function *F, Intrinsic::ID IID,
00050                                              Function *&NewFn) {
00051   // Check that the last argument is an i32.
00052   Type *LastArgType = F->getFunctionType()->getParamType(
00053      F->getFunctionType()->getNumParams() - 1);
00054   if (!LastArgType->isIntegerTy(32))
00055     return false;
00056 
00057   // Move this function aside and map down.
00058   F->setName(F->getName() + ".old");
00059   NewFn = Intrinsic::getDeclaration(F->getParent(), IID);
00060   return true;
00061 }
00062 
00063 // Upgrade the declarations of AVX-512 cmp intrinsic functions whose 8-bit
00064 // immediates have changed their type from i32 to i8.
00065 static bool UpgradeAVX512CmpIntrinsic(Function *F, Intrinsic::ID IID,
00066                                       Function *&NewFn) {
00067   // Check that the last argument is an i32.
00068   Type *LastArgType = F->getFunctionType()->getParamType(2);
00069   if (!LastArgType->isIntegerTy(32))
00070     return false;
00071 
00072   // Move this function aside and map down.
00073   F->setName(F->getName() + ".old");
00074   NewFn = Intrinsic::getDeclaration(F->getParent(), IID);
00075   return true;
00076 }
00077 
00078 static bool UpgradeIntrinsicFunction1(Function *F, Function *&NewFn) {
00079   assert(F && "Illegal to upgrade a non-existent Function.");
00080 
00081   // Quickly eliminate it, if it's not a candidate.
00082   StringRef Name = F->getName();
00083   if (Name.size() <= 8 || !Name.startswith("llvm."))
00084     return false;
00085   Name = Name.substr(5); // Strip off "llvm."
00086 
00087   switch (Name[0]) {
00088   default: break;
00089   case 'a': {
00090     if (Name.startswith("arm.neon.vclz")) {
00091       Type* args[2] = {
00092         F->arg_begin()->getType(),
00093         Type::getInt1Ty(F->getContext())
00094       };
00095       // Can't use Intrinsic::getDeclaration here as it adds a ".i1" to
00096       // the end of the name. Change name from llvm.arm.neon.vclz.* to
00097       //  llvm.ctlz.*
00098       FunctionType* fType = FunctionType::get(F->getReturnType(), args, false);
00099       NewFn = Function::Create(fType, F->getLinkage(),
00100                                "llvm.ctlz." + Name.substr(14), F->getParent());
00101       return true;
00102     }
00103     if (Name.startswith("arm.neon.vcnt")) {
00104       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctpop,
00105                                         F->arg_begin()->getType());
00106       return true;
00107     }
00108     break;
00109   }
00110   case 'c': {
00111     if (Name.startswith("ctlz.") && F->arg_size() == 1) {
00112       F->setName(Name + ".old");
00113       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctlz,
00114                                         F->arg_begin()->getType());
00115       return true;
00116     }
00117     if (Name.startswith("cttz.") && F->arg_size() == 1) {
00118       F->setName(Name + ".old");
00119       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::cttz,
00120                                         F->arg_begin()->getType());
00121       return true;
00122     }
00123     break;
00124   }
00125   case 'd': {
00126     if (Name.startswith("dbg.declare") && F->arg_size() == 2) {
00127       F->setName(Name + ".old");
00128       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::dbg_declare);
00129       return true;
00130     }
00131     if (Name.startswith("dbg.value") && F->arg_size() == 3) {
00132       F->setName(Name + ".old");
00133       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::dbg_value);
00134       return true;
00135     }
00136     break;
00137   }
00138 
00139   case 'o':
00140     // We only need to change the name to match the mangling including the
00141     // address space.
00142     if (F->arg_size() == 2 && Name.startswith("objectsize.")) {
00143       Type *Tys[2] = { F->getReturnType(), F->arg_begin()->getType() };
00144       if (F->getName() != Intrinsic::getName(Intrinsic::objectsize, Tys)) {
00145         F->setName(Name + ".old");
00146         NewFn = Intrinsic::getDeclaration(F->getParent(),
00147                                           Intrinsic::objectsize, Tys);
00148         return true;
00149       }
00150     }
00151     break;
00152 
00153   case 'x': {
00154     if (Name.startswith("x86.sse2.pcmpeq.") ||
00155         Name.startswith("x86.sse2.pcmpgt.") ||
00156         Name.startswith("x86.avx2.pcmpeq.") ||
00157         Name.startswith("x86.avx2.pcmpgt.") ||
00158         Name.startswith("x86.avx.vpermil.") ||
00159         Name == "x86.avx.movnt.dq.256" ||
00160         Name == "x86.avx.movnt.pd.256" ||
00161         Name == "x86.avx.movnt.ps.256" ||
00162         Name == "x86.sse42.crc32.64.8" ||
00163         Name == "x86.avx.vbroadcast.ss" ||
00164         Name == "x86.avx.vbroadcast.ss.256" ||
00165         Name == "x86.avx.vbroadcast.sd.256" ||
00166         (Name.startswith("x86.xop.vpcom") && F->arg_size() == 2)) {
00167       NewFn = nullptr;
00168       return true;
00169     }
00170     // SSE4.1 ptest functions may have an old signature.
00171     if (Name.startswith("x86.sse41.ptest")) {
00172       if (Name == "x86.sse41.ptestc")
00173         return UpgradeSSE41Function(F, Intrinsic::x86_sse41_ptestc, NewFn);
00174       if (Name == "x86.sse41.ptestz")
00175         return UpgradeSSE41Function(F, Intrinsic::x86_sse41_ptestz, NewFn);
00176       if (Name == "x86.sse41.ptestnzc")
00177         return UpgradeSSE41Function(F, Intrinsic::x86_sse41_ptestnzc, NewFn);
00178     }
00179     // Several blend and other instructions with maskes used the wrong number of
00180     // bits.
00181     if (Name == "x86.sse41.pblendw")
00182       return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_pblendw,
00183                                               NewFn);
00184     if (Name == "x86.sse41.blendpd")
00185       return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_blendpd,
00186                                               NewFn);
00187     if (Name == "x86.sse41.blendps")
00188       return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_blendps,
00189                                               NewFn);
00190     if (Name == "x86.sse41.insertps")
00191       return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_insertps,
00192                                               NewFn);
00193     if (Name == "x86.sse41.dppd")
00194       return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_dppd,
00195                                               NewFn);
00196     if (Name == "x86.sse41.dpps")
00197       return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_dpps,
00198                                               NewFn);
00199     if (Name == "x86.sse41.mpsadbw")
00200       return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_mpsadbw,
00201                                               NewFn);
00202     if (Name == "x86.avx.blend.pd.256")
00203       return UpgradeX86IntrinsicsWith8BitMask(
00204           F, Intrinsic::x86_avx_blend_pd_256, NewFn);
00205     if (Name == "x86.avx.blend.ps.256")
00206       return UpgradeX86IntrinsicsWith8BitMask(
00207           F, Intrinsic::x86_avx_blend_ps_256, NewFn);
00208     if (Name == "x86.avx.dp.ps.256")
00209       return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_avx_dp_ps_256,
00210                                               NewFn);
00211     if (Name == "x86.avx2.pblendw")
00212       return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_avx2_pblendw,
00213                                               NewFn);
00214     if (Name == "x86.avx2.pblendd.128")
00215       return UpgradeX86IntrinsicsWith8BitMask(
00216           F, Intrinsic::x86_avx2_pblendd_128, NewFn);
00217     if (Name == "x86.avx2.pblendd.256")
00218       return UpgradeX86IntrinsicsWith8BitMask(
00219           F, Intrinsic::x86_avx2_pblendd_256, NewFn);
00220     if (Name == "x86.avx2.mpsadbw")
00221       return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_avx2_mpsadbw,
00222                                               NewFn);
00223 
00224     if (Name == "x86.avx512.mask.cmp.ps.512")
00225       return UpgradeAVX512CmpIntrinsic(F, Intrinsic::x86_avx512_mask_cmp_ps_512,
00226                                        NewFn);
00227     if (Name == "x86.avx512.mask.cmp.pd.512")
00228       return UpgradeAVX512CmpIntrinsic(F, Intrinsic::x86_avx512_mask_cmp_pd_512,
00229                                        NewFn);
00230 
00231     // frcz.ss/sd may need to have an argument dropped
00232     if (Name.startswith("x86.xop.vfrcz.ss") && F->arg_size() == 2) {
00233       F->setName(Name + ".old");
00234       NewFn = Intrinsic::getDeclaration(F->getParent(),
00235                                         Intrinsic::x86_xop_vfrcz_ss);
00236       return true;
00237     }
00238     if (Name.startswith("x86.xop.vfrcz.sd") && F->arg_size() == 2) {
00239       F->setName(Name + ".old");
00240       NewFn = Intrinsic::getDeclaration(F->getParent(),
00241                                         Intrinsic::x86_xop_vfrcz_sd);
00242       return true;
00243     }
00244     // Fix the FMA4 intrinsics to remove the 4
00245     if (Name.startswith("x86.fma4.")) {
00246       F->setName("llvm.x86.fma" + Name.substr(8));
00247       NewFn = F;
00248       return true;
00249     }
00250     break;
00251   }
00252   }
00253 
00254   //  This may not belong here. This function is effectively being overloaded
00255   //  to both detect an intrinsic which needs upgrading, and to provide the
00256   //  upgraded form of the intrinsic. We should perhaps have two separate
00257   //  functions for this.
00258   return false;
00259 }
00260 
00261 bool llvm::UpgradeIntrinsicFunction(Function *F, Function *&NewFn) {
00262   NewFn = nullptr;
00263   bool Upgraded = UpgradeIntrinsicFunction1(F, NewFn);
00264 
00265   // Upgrade intrinsic attributes.  This does not change the function.
00266   if (NewFn)
00267     F = NewFn;
00268   if (unsigned id = F->getIntrinsicID())
00269     F->setAttributes(Intrinsic::getAttributes(F->getContext(),
00270                                               (Intrinsic::ID)id));
00271   return Upgraded;
00272 }
00273 
00274 bool llvm::UpgradeGlobalVariable(GlobalVariable *GV) {
00275   // Nothing to do yet.
00276   return false;
00277 }
00278 
00279 static MDNode *getNodeField(const MDNode *DbgNode, unsigned Elt) {
00280   if (!DbgNode || Elt >= DbgNode->getNumOperands())
00281     return nullptr;
00282   return dyn_cast_or_null<MDNode>(DbgNode->getOperand(Elt));
00283 }
00284 
00285 static MetadataAsValue *getExpression(Value *VarOperand, Function *F) {
00286   // Old-style DIVariables have an optional expression as the 8th element.
00287   DIExpression Expr(getNodeField(
00288       cast<MDNode>(cast<MetadataAsValue>(VarOperand)->getMetadata()), 8));
00289   if (!Expr) {
00290     DIBuilder DIB(*F->getParent(), /*AllowUnresolved*/ false);
00291     Expr = DIB.createExpression();
00292   }
00293   return MetadataAsValue::get(F->getContext(), Expr);
00294 }
00295 
00296 // UpgradeIntrinsicCall - Upgrade a call to an old intrinsic to be a call the
00297 // upgraded intrinsic. All argument and return casting must be provided in
00298 // order to seamlessly integrate with existing context.
00299 void llvm::UpgradeIntrinsicCall(CallInst *CI, Function *NewFn) {
00300   Function *F = CI->getCalledFunction();
00301   LLVMContext &C = CI->getContext();
00302   IRBuilder<> Builder(C);
00303   Builder.SetInsertPoint(CI->getParent(), CI);
00304 
00305   assert(F && "Intrinsic call is not direct?");
00306 
00307   if (!NewFn) {
00308     // Get the Function's name.
00309     StringRef Name = F->getName();
00310 
00311     Value *Rep;
00312     // Upgrade packed integer vector compares intrinsics to compare instructions
00313     if (Name.startswith("llvm.x86.sse2.pcmpeq.") ||
00314         Name.startswith("llvm.x86.avx2.pcmpeq.")) {
00315       Rep = Builder.CreateICmpEQ(CI->getArgOperand(0), CI->getArgOperand(1),
00316                                  "pcmpeq");
00317       // need to sign extend since icmp returns vector of i1
00318       Rep = Builder.CreateSExt(Rep, CI->getType(), "");
00319     } else if (Name.startswith("llvm.x86.sse2.pcmpgt.") ||
00320                Name.startswith("llvm.x86.avx2.pcmpgt.")) {
00321       Rep = Builder.CreateICmpSGT(CI->getArgOperand(0), CI->getArgOperand(1),
00322                                   "pcmpgt");
00323       // need to sign extend since icmp returns vector of i1
00324       Rep = Builder.CreateSExt(Rep, CI->getType(), "");
00325     } else if (Name == "llvm.x86.avx.movnt.dq.256" ||
00326                Name == "llvm.x86.avx.movnt.ps.256" ||
00327                Name == "llvm.x86.avx.movnt.pd.256") {
00328       IRBuilder<> Builder(C);
00329       Builder.SetInsertPoint(CI->getParent(), CI);
00330 
00331       Module *M = F->getParent();
00332       SmallVector<Metadata *, 1> Elts;
00333       Elts.push_back(
00334           ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(C), 1)));
00335       MDNode *Node = MDNode::get(C, Elts);
00336 
00337       Value *Arg0 = CI->getArgOperand(0);
00338       Value *Arg1 = CI->getArgOperand(1);
00339 
00340       // Convert the type of the pointer to a pointer to the stored type.
00341       Value *BC = Builder.CreateBitCast(Arg0,
00342                                         PointerType::getUnqual(Arg1->getType()),
00343                                         "cast");
00344       StoreInst *SI = Builder.CreateStore(Arg1, BC);
00345       SI->setMetadata(M->getMDKindID("nontemporal"), Node);
00346       SI->setAlignment(16);
00347 
00348       // Remove intrinsic.
00349       CI->eraseFromParent();
00350       return;
00351     } else if (Name.startswith("llvm.x86.xop.vpcom")) {
00352       Intrinsic::ID intID;
00353       if (Name.endswith("ub"))
00354         intID = Intrinsic::x86_xop_vpcomub;
00355       else if (Name.endswith("uw"))
00356         intID = Intrinsic::x86_xop_vpcomuw;
00357       else if (Name.endswith("ud"))
00358         intID = Intrinsic::x86_xop_vpcomud;
00359       else if (Name.endswith("uq"))
00360         intID = Intrinsic::x86_xop_vpcomuq;
00361       else if (Name.endswith("b"))
00362         intID = Intrinsic::x86_xop_vpcomb;
00363       else if (Name.endswith("w"))
00364         intID = Intrinsic::x86_xop_vpcomw;
00365       else if (Name.endswith("d"))
00366         intID = Intrinsic::x86_xop_vpcomd;
00367       else if (Name.endswith("q"))
00368         intID = Intrinsic::x86_xop_vpcomq;
00369       else
00370         llvm_unreachable("Unknown suffix");
00371 
00372       Name = Name.substr(18); // strip off "llvm.x86.xop.vpcom"
00373       unsigned Imm;
00374       if (Name.startswith("lt"))
00375         Imm = 0;
00376       else if (Name.startswith("le"))
00377         Imm = 1;
00378       else if (Name.startswith("gt"))
00379         Imm = 2;
00380       else if (Name.startswith("ge"))
00381         Imm = 3;
00382       else if (Name.startswith("eq"))
00383         Imm = 4;
00384       else if (Name.startswith("ne"))
00385         Imm = 5;
00386       else if (Name.startswith("true"))
00387         Imm = 6;
00388       else if (Name.startswith("false"))
00389         Imm = 7;
00390       else
00391         llvm_unreachable("Unknown condition");
00392 
00393       Function *VPCOM = Intrinsic::getDeclaration(F->getParent(), intID);
00394       Rep = Builder.CreateCall3(VPCOM, CI->getArgOperand(0),
00395                                 CI->getArgOperand(1), Builder.getInt8(Imm));
00396     } else if (Name == "llvm.x86.sse42.crc32.64.8") {
00397       Function *CRC32 = Intrinsic::getDeclaration(F->getParent(),
00398                                                Intrinsic::x86_sse42_crc32_32_8);
00399       Value *Trunc0 = Builder.CreateTrunc(CI->getArgOperand(0), Type::getInt32Ty(C));
00400       Rep = Builder.CreateCall2(CRC32, Trunc0, CI->getArgOperand(1));
00401       Rep = Builder.CreateZExt(Rep, CI->getType(), "");
00402     } else if (Name.startswith("llvm.x86.avx.vbroadcast")) {
00403       // Replace broadcasts with a series of insertelements.
00404       Type *VecTy = CI->getType();
00405       Type *EltTy = VecTy->getVectorElementType();
00406       unsigned EltNum = VecTy->getVectorNumElements();
00407       Value *Cast = Builder.CreateBitCast(CI->getArgOperand(0),
00408                                           EltTy->getPointerTo());
00409       Value *Load = Builder.CreateLoad(Cast);
00410       Type *I32Ty = Type::getInt32Ty(C);
00411       Rep = UndefValue::get(VecTy);
00412       for (unsigned I = 0; I < EltNum; ++I)
00413         Rep = Builder.CreateInsertElement(Rep, Load,
00414                                           ConstantInt::get(I32Ty, I));
00415     } else {
00416       bool PD128 = false, PD256 = false, PS128 = false, PS256 = false;
00417       if (Name == "llvm.x86.avx.vpermil.pd.256")
00418         PD256 = true;
00419       else if (Name == "llvm.x86.avx.vpermil.pd")
00420         PD128 = true;
00421       else if (Name == "llvm.x86.avx.vpermil.ps.256")
00422         PS256 = true;
00423       else if (Name == "llvm.x86.avx.vpermil.ps")
00424         PS128 = true;
00425 
00426       if (PD256 || PD128 || PS256 || PS128) {
00427         Value *Op0 = CI->getArgOperand(0);
00428         unsigned Imm = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
00429         SmallVector<Constant*, 8> Idxs;
00430 
00431         if (PD128)
00432           for (unsigned i = 0; i != 2; ++i)
00433             Idxs.push_back(Builder.getInt32((Imm >> i) & 0x1));
00434         else if (PD256)
00435           for (unsigned l = 0; l != 4; l+=2)
00436             for (unsigned i = 0; i != 2; ++i)
00437               Idxs.push_back(Builder.getInt32(((Imm >> (l+i)) & 0x1) + l));
00438         else if (PS128)
00439           for (unsigned i = 0; i != 4; ++i)
00440             Idxs.push_back(Builder.getInt32((Imm >> (2 * i)) & 0x3));
00441         else if (PS256)
00442           for (unsigned l = 0; l != 8; l+=4)
00443             for (unsigned i = 0; i != 4; ++i)
00444               Idxs.push_back(Builder.getInt32(((Imm >> (2 * i)) & 0x3) + l));
00445         else
00446           llvm_unreachable("Unexpected function");
00447 
00448         Rep = Builder.CreateShuffleVector(Op0, Op0, ConstantVector::get(Idxs));
00449       } else {
00450         llvm_unreachable("Unknown function for CallInst upgrade.");
00451       }
00452     }
00453 
00454     CI->replaceAllUsesWith(Rep);
00455     CI->eraseFromParent();
00456     return;
00457   }
00458 
00459   std::string Name = CI->getName().str();
00460   if (!Name.empty())
00461     CI->setName(Name + ".old");
00462 
00463   switch (NewFn->getIntrinsicID()) {
00464   default:
00465     llvm_unreachable("Unknown function for CallInst upgrade.");
00466 
00467   // Upgrade debug intrinsics to use an additional DIExpression argument.
00468   case Intrinsic::dbg_declare: {
00469     auto NewCI =
00470         Builder.CreateCall3(NewFn, CI->getArgOperand(0), CI->getArgOperand(1),
00471                             getExpression(CI->getArgOperand(1), F), Name);
00472     NewCI->setDebugLoc(CI->getDebugLoc());
00473     CI->replaceAllUsesWith(NewCI);
00474     CI->eraseFromParent();
00475     return;
00476   }
00477   case Intrinsic::dbg_value: {
00478     auto NewCI = Builder.CreateCall4(
00479         NewFn, CI->getArgOperand(0), CI->getArgOperand(1), CI->getArgOperand(2),
00480         getExpression(CI->getArgOperand(2), F), Name);
00481     NewCI->setDebugLoc(CI->getDebugLoc());
00482     CI->replaceAllUsesWith(NewCI);
00483     CI->eraseFromParent();
00484     return;
00485   }
00486   case Intrinsic::ctlz:
00487   case Intrinsic::cttz:
00488     assert(CI->getNumArgOperands() == 1 &&
00489            "Mismatch between function args and call args");
00490     CI->replaceAllUsesWith(Builder.CreateCall2(NewFn, CI->getArgOperand(0),
00491                                                Builder.getFalse(), Name));
00492     CI->eraseFromParent();
00493     return;
00494 
00495   case Intrinsic::objectsize:
00496     CI->replaceAllUsesWith(Builder.CreateCall2(NewFn,
00497                                                CI->getArgOperand(0),
00498                                                CI->getArgOperand(1),
00499                                                Name));
00500     CI->eraseFromParent();
00501     return;
00502 
00503   case Intrinsic::ctpop: {
00504     CI->replaceAllUsesWith(Builder.CreateCall(NewFn, CI->getArgOperand(0)));
00505     CI->eraseFromParent();
00506     return;
00507   }
00508 
00509   case Intrinsic::x86_xop_vfrcz_ss:
00510   case Intrinsic::x86_xop_vfrcz_sd:
00511     CI->replaceAllUsesWith(Builder.CreateCall(NewFn, CI->getArgOperand(1),
00512                                               Name));
00513     CI->eraseFromParent();
00514     return;
00515 
00516   case Intrinsic::x86_sse41_ptestc:
00517   case Intrinsic::x86_sse41_ptestz:
00518   case Intrinsic::x86_sse41_ptestnzc: {
00519     // The arguments for these intrinsics used to be v4f32, and changed
00520     // to v2i64. This is purely a nop, since those are bitwise intrinsics.
00521     // So, the only thing required is a bitcast for both arguments.
00522     // First, check the arguments have the old type.
00523     Value *Arg0 = CI->getArgOperand(0);
00524     if (Arg0->getType() != VectorType::get(Type::getFloatTy(C), 4))
00525       return;
00526 
00527     // Old intrinsic, add bitcasts
00528     Value *Arg1 = CI->getArgOperand(1);
00529 
00530     Value *BC0 =
00531       Builder.CreateBitCast(Arg0,
00532                             VectorType::get(Type::getInt64Ty(C), 2),
00533                             "cast");
00534     Value *BC1 =
00535       Builder.CreateBitCast(Arg1,
00536                             VectorType::get(Type::getInt64Ty(C), 2),
00537                             "cast");
00538 
00539     CallInst* NewCall = Builder.CreateCall2(NewFn, BC0, BC1, Name);
00540     CI->replaceAllUsesWith(NewCall);
00541     CI->eraseFromParent();
00542     return;
00543   }
00544 
00545   case Intrinsic::x86_sse41_pblendw:
00546   case Intrinsic::x86_sse41_blendpd:
00547   case Intrinsic::x86_sse41_blendps:
00548   case Intrinsic::x86_sse41_insertps:
00549   case Intrinsic::x86_sse41_dppd:
00550   case Intrinsic::x86_sse41_dpps:
00551   case Intrinsic::x86_sse41_mpsadbw:
00552   case Intrinsic::x86_avx_blend_pd_256:
00553   case Intrinsic::x86_avx_blend_ps_256:
00554   case Intrinsic::x86_avx_dp_ps_256:
00555   case Intrinsic::x86_avx2_pblendw:
00556   case Intrinsic::x86_avx2_pblendd_128:
00557   case Intrinsic::x86_avx2_pblendd_256:
00558   case Intrinsic::x86_avx2_mpsadbw: {
00559     // Need to truncate the last argument from i32 to i8 -- this argument models
00560     // an inherently 8-bit immediate operand to these x86 instructions.
00561     SmallVector<Value *, 4> Args(CI->arg_operands().begin(),
00562                                  CI->arg_operands().end());
00563 
00564     // Replace the last argument with a trunc.
00565     Args.back() = Builder.CreateTrunc(Args.back(), Type::getInt8Ty(C), "trunc");
00566 
00567     CallInst *NewCall = Builder.CreateCall(NewFn, Args);
00568     CI->replaceAllUsesWith(NewCall);
00569     CI->eraseFromParent();
00570     return;
00571   }
00572   case Intrinsic::x86_avx512_mask_cmp_ps_512:
00573   case Intrinsic::x86_avx512_mask_cmp_pd_512: {
00574     // Need to truncate the last argument from i32 to i8 -- this argument models
00575     // an inherently 8-bit immediate operand to these x86 instructions.
00576     SmallVector<Value *, 5> Args(CI->arg_operands().begin(),
00577                                  CI->arg_operands().end());
00578 
00579     // Replace the last argument with a trunc.
00580     Args[2] = Builder.CreateTrunc(Args[2], Type::getInt8Ty(C), "trunc");
00581 
00582     CallInst *NewCall = Builder.CreateCall(NewFn, Args);
00583     CI->replaceAllUsesWith(NewCall);
00584     CI->eraseFromParent();
00585     return;
00586   }
00587   }
00588 }
00589 
00590 // This tests each Function to determine if it needs upgrading. When we find
00591 // one we are interested in, we then upgrade all calls to reflect the new
00592 // function.
00593 void llvm::UpgradeCallsToIntrinsic(Function* F) {
00594   assert(F && "Illegal attempt to upgrade a non-existent intrinsic.");
00595 
00596   // Upgrade the function and check if it is a totaly new function.
00597   Function *NewFn;
00598   if (UpgradeIntrinsicFunction(F, NewFn)) {
00599     if (NewFn != F) {
00600       // Replace all uses to the old function with the new one if necessary.
00601       for (Value::user_iterator UI = F->user_begin(), UE = F->user_end();
00602            UI != UE; ) {
00603         if (CallInst *CI = dyn_cast<CallInst>(*UI++))
00604           UpgradeIntrinsicCall(CI, NewFn);
00605       }
00606       // Remove old function, no longer used, from the module.
00607       F->eraseFromParent();
00608     }
00609   }
00610 }
00611 
00612 void llvm::UpgradeInstWithTBAATag(Instruction *I) {
00613   MDNode *MD = I->getMetadata(LLVMContext::MD_tbaa);
00614   assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
00615   // Check if the tag uses struct-path aware TBAA format.
00616   if (isa<MDNode>(MD->getOperand(0)) && MD->getNumOperands() >= 3)
00617     return;
00618 
00619   if (MD->getNumOperands() == 3) {
00620     Metadata *Elts[] = {MD->getOperand(0), MD->getOperand(1)};
00621     MDNode *ScalarType = MDNode::get(I->getContext(), Elts);
00622     // Create a MDNode <ScalarType, ScalarType, offset 0, const>
00623     Metadata *Elts2[] = {ScalarType, ScalarType,
00624                          ConstantAsMetadata::get(Constant::getNullValue(
00625                              Type::getInt64Ty(I->getContext()))),
00626                          MD->getOperand(2)};
00627     I->setMetadata(LLVMContext::MD_tbaa, MDNode::get(I->getContext(), Elts2));
00628   } else {
00629     // Create a MDNode <MD, MD, offset 0>
00630     Metadata *Elts[] = {MD, MD, ConstantAsMetadata::get(Constant::getNullValue(
00631                                     Type::getInt64Ty(I->getContext())))};
00632     I->setMetadata(LLVMContext::MD_tbaa, MDNode::get(I->getContext(), Elts));
00633   }
00634 }
00635 
00636 Instruction *llvm::UpgradeBitCastInst(unsigned Opc, Value *V, Type *DestTy,
00637                                       Instruction *&Temp) {
00638   if (Opc != Instruction::BitCast)
00639     return nullptr;
00640 
00641   Temp = nullptr;
00642   Type *SrcTy = V->getType();
00643   if (SrcTy->isPtrOrPtrVectorTy() && DestTy->isPtrOrPtrVectorTy() &&
00644       SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace()) {
00645     LLVMContext &Context = V->getContext();
00646 
00647     // We have no information about target data layout, so we assume that
00648     // the maximum pointer size is 64bit.
00649     Type *MidTy = Type::getInt64Ty(Context);
00650     Temp = CastInst::Create(Instruction::PtrToInt, V, MidTy);
00651 
00652     return CastInst::Create(Instruction::IntToPtr, Temp, DestTy);
00653   }
00654 
00655   return nullptr;
00656 }
00657 
00658 Value *llvm::UpgradeBitCastExpr(unsigned Opc, Constant *C, Type *DestTy) {
00659   if (Opc != Instruction::BitCast)
00660     return nullptr;
00661 
00662   Type *SrcTy = C->getType();
00663   if (SrcTy->isPtrOrPtrVectorTy() && DestTy->isPtrOrPtrVectorTy() &&
00664       SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace()) {
00665     LLVMContext &Context = C->getContext();
00666 
00667     // We have no information about target data layout, so we assume that
00668     // the maximum pointer size is 64bit.
00669     Type *MidTy = Type::getInt64Ty(Context);
00670 
00671     return ConstantExpr::getIntToPtr(ConstantExpr::getPtrToInt(C, MidTy),
00672                                      DestTy);
00673   }
00674 
00675   return nullptr;
00676 }
00677 
00678 /// Check the debug info version number, if it is out-dated, drop the debug
00679 /// info. Return true if module is modified.
00680 bool llvm::UpgradeDebugInfo(Module &M) {
00681   unsigned Version = getDebugMetadataVersionFromModule(M);
00682   if (Version == DEBUG_METADATA_VERSION)
00683     return false;
00684 
00685   bool RetCode = StripDebugInfo(M);
00686   if (RetCode) {
00687     DiagnosticInfoDebugMetadataVersion DiagVersion(M, Version);
00688     M.getContext().diagnose(DiagVersion);
00689   }
00690   return RetCode;
00691 }
00692 
00693 void llvm::UpgradeMDStringConstant(std::string &String) {
00694   const std::string OldPrefix = "llvm.vectorizer.";
00695   if (String == "llvm.vectorizer.unroll") {
00696     String = "llvm.loop.interleave.count";
00697   } else if (String.find(OldPrefix) == 0) {
00698     String.replace(0, OldPrefix.size(), "llvm.loop.vectorize.");
00699   }
00700 }