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