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/AutoUpgrade.h"
00015 #include "llvm/Constants.h"
00016 #include "llvm/Function.h"
00017 #include "llvm/LLVMContext.h"
00018 #include "llvm/Module.h"
00019 #include "llvm/Instructions.h"
00020 #include "llvm/Intrinsics.h"
00021 #include "llvm/ADT/SmallVector.h"
00022 #include "llvm/Support/ErrorHandling.h"
00023 #include <cstring>
00024 using namespace llvm;
00025 
00026 
00027 static bool UpgradeIntrinsicFunction1(Function *F, Function *&NewFn) {
00028   assert(F && "Illegal to upgrade a non-existent Function.");
00029 
00030   // Get the Function's name.
00031   const std::string& Name = F->getName();
00032 
00033   // Convenience
00034   const FunctionType *FTy = F->getFunctionType();
00035 
00036   // Quickly eliminate it, if it's not a candidate.
00037   if (Name.length() <= 8 || Name[0] != 'l' || Name[1] != 'l' || 
00038       Name[2] != 'v' || Name[3] != 'm' || Name[4] != '.')
00039     return false;
00040 
00041   Module *M = F->getParent();
00042   switch (Name[5]) {
00043   default: break;
00044   case 'a':
00045     // This upgrades the llvm.atomic.lcs, llvm.atomic.las, llvm.atomic.lss,
00046     // and atomics with default address spaces to their new names to their new
00047     // function name (e.g. llvm.atomic.add.i32 => llvm.atomic.add.i32.p0i32)
00048     if (Name.compare(5,7,"atomic.",7) == 0) {
00049       if (Name.compare(12,3,"lcs",3) == 0) {
00050         std::string::size_type delim = Name.find('.',12);
00051         F->setName("llvm.atomic.cmp.swap" + Name.substr(delim) +
00052                    ".p0" + Name.substr(delim+1));
00053         NewFn = F;
00054         return true;
00055       }
00056       else if (Name.compare(12,3,"las",3) == 0) {
00057         std::string::size_type delim = Name.find('.',12);
00058         F->setName("llvm.atomic.load.add"+Name.substr(delim)
00059                    + ".p0" + Name.substr(delim+1));
00060         NewFn = F;
00061         return true;
00062       }
00063       else if (Name.compare(12,3,"lss",3) == 0) {
00064         std::string::size_type delim = Name.find('.',12);
00065         F->setName("llvm.atomic.load.sub"+Name.substr(delim)
00066                    + ".p0" + Name.substr(delim+1));
00067         NewFn = F;
00068         return true;
00069       }
00070       else if (Name.rfind(".p") == std::string::npos) {
00071         // We don't have an address space qualifier so this has be upgraded
00072         // to the new name.  Copy the type name at the end of the intrinsic
00073         // and add to it
00074         std::string::size_type delim = Name.find_last_of('.');
00075         assert(delim != std::string::npos && "can not find type");
00076         F->setName(Name + ".p0" + Name.substr(delim+1));
00077         NewFn = F;
00078         return true;
00079       }
00080     }
00081     break;
00082   case 'b':
00083     //  This upgrades the name of the llvm.bswap intrinsic function to only use 
00084     //  a single type name for overloading. We only care about the old format
00085     //  'llvm.bswap.i*.i*', so check for 'bswap.' and then for there being 
00086     //  a '.' after 'bswap.'
00087     if (Name.compare(5,6,"bswap.",6) == 0) {
00088       std::string::size_type delim = Name.find('.',11);
00089       
00090       if (delim != std::string::npos) {
00091         //  Construct the new name as 'llvm.bswap' + '.i*'
00092         F->setName(Name.substr(0,10)+Name.substr(delim));
00093         NewFn = F;
00094         return true;
00095       }
00096     }
00097     break;
00098 
00099   case 'c':
00100     //  We only want to fix the 'llvm.ct*' intrinsics which do not have the 
00101     //  correct return type, so we check for the name, and then check if the 
00102     //  return type does not match the parameter type.
00103     if ( (Name.compare(5,5,"ctpop",5) == 0 ||
00104           Name.compare(5,4,"ctlz",4) == 0 ||
00105           Name.compare(5,4,"cttz",4) == 0) &&
00106         FTy->getReturnType() != FTy->getParamType(0)) {
00107       //  We first need to change the name of the old (bad) intrinsic, because 
00108       //  its type is incorrect, but we cannot overload that name. We 
00109       //  arbitrarily unique it here allowing us to construct a correctly named 
00110       //  and typed function below.
00111       F->setName("");
00112 
00113       //  Now construct the new intrinsic with the correct name and type. We 
00114       //  leave the old function around in order to query its type, whatever it 
00115       //  may be, and correctly convert up to the new type.
00116       NewFn = cast<Function>(M->getOrInsertFunction(Name, 
00117                                                     FTy->getParamType(0),
00118                                                     FTy->getParamType(0),
00119                                                     (Type *)0));
00120       return true;
00121     }
00122     break;
00123 
00124   case 'p':
00125     //  This upgrades the llvm.part.select overloaded intrinsic names to only 
00126     //  use one type specifier in the name. We only care about the old format
00127     //  'llvm.part.select.i*.i*', and solve as above with bswap.
00128     if (Name.compare(5,12,"part.select.",12) == 0) {
00129       std::string::size_type delim = Name.find('.',17);
00130       
00131       if (delim != std::string::npos) {
00132         //  Construct a new name as 'llvm.part.select' + '.i*'
00133         F->setName(Name.substr(0,16)+Name.substr(delim));
00134         NewFn = F;
00135         return true;
00136       }
00137       break;
00138     }
00139 
00140     //  This upgrades the llvm.part.set intrinsics similarly as above, however 
00141     //  we care about 'llvm.part.set.i*.i*.i*', but only the first two types 
00142     //  must match. There is an additional type specifier after these two 
00143     //  matching types that we must retain when upgrading.  Thus, we require 
00144     //  finding 2 periods, not just one, after the intrinsic name.
00145     if (Name.compare(5,9,"part.set.",9) == 0) {
00146       std::string::size_type delim = Name.find('.',14);
00147 
00148       if (delim != std::string::npos &&
00149           Name.find('.',delim+1) != std::string::npos) {
00150         //  Construct a new name as 'llvm.part.select' + '.i*.i*'
00151         F->setName(Name.substr(0,13)+Name.substr(delim));
00152         NewFn = F;
00153         return true;
00154       }
00155       break;
00156     }
00157 
00158     break;
00159   case 'x': 
00160     // This fixes all MMX shift intrinsic instructions to take a
00161     // v1i64 instead of a v2i32 as the second parameter.
00162     if (Name.compare(5,10,"x86.mmx.ps",10) == 0 &&
00163         (Name.compare(13,4,"psll", 4) == 0 ||
00164          Name.compare(13,4,"psra", 4) == 0 ||
00165          Name.compare(13,4,"psrl", 4) == 0) && Name[17] != 'i') {
00166       
00167       const llvm::Type *VT =
00168                     VectorType::get(IntegerType::get(FTy->getContext(), 64), 1);
00169       
00170       // We don't have to do anything if the parameter already has
00171       // the correct type.
00172       if (FTy->getParamType(1) == VT)
00173         break;
00174       
00175       //  We first need to change the name of the old (bad) intrinsic, because 
00176       //  its type is incorrect, but we cannot overload that name. We 
00177       //  arbitrarily unique it here allowing us to construct a correctly named 
00178       //  and typed function below.
00179       F->setName("");
00180 
00181       assert(FTy->getNumParams() == 2 && "MMX shift intrinsics take 2 args!");
00182       
00183       //  Now construct the new intrinsic with the correct name and type. We 
00184       //  leave the old function around in order to query its type, whatever it 
00185       //  may be, and correctly convert up to the new type.
00186       NewFn = cast<Function>(M->getOrInsertFunction(Name, 
00187                                                     FTy->getReturnType(),
00188                                                     FTy->getParamType(0),
00189                                                     VT,
00190                                                     (Type *)0));
00191       return true;
00192     } else if (Name.compare(5,17,"x86.sse2.loadh.pd",17) == 0 ||
00193                Name.compare(5,17,"x86.sse2.loadl.pd",17) == 0 ||
00194                Name.compare(5,16,"x86.sse2.movl.dq",16) == 0 ||
00195                Name.compare(5,15,"x86.sse2.movs.d",15) == 0 ||
00196                Name.compare(5,16,"x86.sse2.shuf.pd",16) == 0 ||
00197                Name.compare(5,18,"x86.sse2.unpckh.pd",18) == 0 ||
00198                Name.compare(5,18,"x86.sse2.unpckl.pd",18) == 0 ||
00199                Name.compare(5,20,"x86.sse2.punpckh.qdq",20) == 0 ||
00200                Name.compare(5,20,"x86.sse2.punpckl.qdq",20) == 0) {
00201       // Calls to these intrinsics are transformed into ShuffleVector's.
00202       NewFn = 0;
00203       return true;
00204     }
00205 
00206     break;
00207   }
00208 
00209   //  This may not belong here. This function is effectively being overloaded 
00210   //  to both detect an intrinsic which needs upgrading, and to provide the 
00211   //  upgraded form of the intrinsic. We should perhaps have two separate 
00212   //  functions for this.
00213   return false;
00214 }
00215 
00216 bool llvm::UpgradeIntrinsicFunction(Function *F, Function *&NewFn) {
00217   NewFn = 0;
00218   bool Upgraded = UpgradeIntrinsicFunction1(F, NewFn);
00219 
00220   // Upgrade intrinsic attributes.  This does not change the function.
00221   if (NewFn)
00222     F = NewFn;
00223   if (unsigned id = F->getIntrinsicID())
00224     F->setAttributes(Intrinsic::getAttributes((Intrinsic::ID)id));
00225   return Upgraded;
00226 }
00227 
00228 // UpgradeIntrinsicCall - Upgrade a call to an old intrinsic to be a call the 
00229 // upgraded intrinsic. All argument and return casting must be provided in 
00230 // order to seamlessly integrate with existing context.
00231 void llvm::UpgradeIntrinsicCall(CallInst *CI, Function *NewFn) {
00232   Function *F = CI->getCalledFunction();
00233   LLVMContext &C = CI->getContext();
00234   
00235   assert(F && "CallInst has no function associated with it.");
00236 
00237   if (!NewFn) {
00238     bool isLoadH = false, isLoadL = false, isMovL = false;
00239     bool isMovSD = false, isShufPD = false;
00240     bool isUnpckhPD = false, isUnpcklPD = false;
00241     bool isPunpckhQPD = false, isPunpcklQPD = false;
00242     if (F->getName() == "llvm.x86.sse2.loadh.pd")
00243       isLoadH = true;
00244     else if (F->getName() == "llvm.x86.sse2.loadl.pd")
00245       isLoadL = true;
00246     else if (F->getName() == "llvm.x86.sse2.movl.dq")
00247       isMovL = true;
00248     else if (F->getName() == "llvm.x86.sse2.movs.d")
00249       isMovSD = true;
00250     else if (F->getName() == "llvm.x86.sse2.shuf.pd")
00251       isShufPD = true;
00252     else if (F->getName() == "llvm.x86.sse2.unpckh.pd")
00253       isUnpckhPD = true;
00254     else if (F->getName() == "llvm.x86.sse2.unpckl.pd")
00255       isUnpcklPD = true;
00256     else if (F->getName() ==  "llvm.x86.sse2.punpckh.qdq")
00257       isPunpckhQPD = true;
00258     else if (F->getName() ==  "llvm.x86.sse2.punpckl.qdq")
00259       isPunpcklQPD = true;
00260 
00261     if (isLoadH || isLoadL || isMovL || isMovSD || isShufPD ||
00262         isUnpckhPD || isUnpcklPD || isPunpckhQPD || isPunpcklQPD) {
00263       std::vector<Constant*> Idxs;
00264       Value *Op0 = CI->getOperand(1);
00265       ShuffleVectorInst *SI = NULL;
00266       if (isLoadH || isLoadL) {
00267         Value *Op1 = UndefValue::get(Op0->getType());
00268         Value *Addr = new BitCastInst(CI->getOperand(2), 
00269                                   PointerType::getUnqual(Type::getDoubleTy(C)),
00270                                       "upgraded.", CI);
00271         Value *Load = new LoadInst(Addr, "upgraded.", false, 8, CI);
00272         Value *Idx = ConstantInt::get(Type::getInt32Ty(C), 0);
00273         Op1 = InsertElementInst::Create(Op1, Load, Idx, "upgraded.", CI);
00274 
00275         if (isLoadH) {
00276           Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), 0));
00277           Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), 2));
00278         } else {
00279           Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), 2));
00280           Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), 1));
00281         }
00282         Value *Mask = ConstantVector::get(Idxs);
00283         SI = new ShuffleVectorInst(Op0, Op1, Mask, "upgraded.", CI);
00284       } else if (isMovL) {
00285         Constant *Zero = ConstantInt::get(Type::getInt32Ty(C), 0);
00286         Idxs.push_back(Zero);
00287         Idxs.push_back(Zero);
00288         Idxs.push_back(Zero);
00289         Idxs.push_back(Zero);
00290         Value *ZeroV = ConstantVector::get(Idxs);
00291 
00292         Idxs.clear(); 
00293         Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), 4));
00294         Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), 5));
00295         Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), 2));
00296         Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), 3));
00297         Value *Mask = ConstantVector::get(Idxs);
00298         SI = new ShuffleVectorInst(ZeroV, Op0, Mask, "upgraded.", CI);
00299       } else if (isMovSD ||
00300                  isUnpckhPD || isUnpcklPD || isPunpckhQPD || isPunpcklQPD) {
00301         Value *Op1 = CI->getOperand(2);
00302         if (isMovSD) {
00303           Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), 2));
00304           Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), 1));
00305         } else if (isUnpckhPD || isPunpckhQPD) {
00306           Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), 1));
00307           Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), 3));
00308         } else {
00309           Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), 0));
00310           Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), 2));
00311         }
00312         Value *Mask = ConstantVector::get(Idxs);
00313         SI = new ShuffleVectorInst(Op0, Op1, Mask, "upgraded.", CI);
00314       } else if (isShufPD) {
00315         Value *Op1 = CI->getOperand(2);
00316         unsigned MaskVal = cast<ConstantInt>(CI->getOperand(3))->getZExtValue();
00317         Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C), MaskVal & 1));
00318         Idxs.push_back(ConstantInt::get(Type::getInt32Ty(C),
00319                                                ((MaskVal >> 1) & 1)+2));
00320         Value *Mask = ConstantVector::get(Idxs);
00321         SI = new ShuffleVectorInst(Op0, Op1, Mask, "upgraded.", CI);
00322       }
00323 
00324       assert(SI && "Unexpected!");
00325 
00326       // Handle any uses of the old CallInst.
00327       if (!CI->use_empty())
00328         //  Replace all uses of the old call with the new cast which has the 
00329         //  correct type.
00330         CI->replaceAllUsesWith(SI);
00331       
00332       //  Clean up the old call now that it has been completely upgraded.
00333       CI->eraseFromParent();
00334     } else {
00335       llvm_unreachable("Unknown function for CallInst upgrade.");
00336     }
00337     return;
00338   }
00339 
00340   switch (NewFn->getIntrinsicID()) {
00341   default:  llvm_unreachable("Unknown function for CallInst upgrade.");
00342   case Intrinsic::x86_mmx_psll_d:
00343   case Intrinsic::x86_mmx_psll_q:
00344   case Intrinsic::x86_mmx_psll_w:
00345   case Intrinsic::x86_mmx_psra_d:
00346   case Intrinsic::x86_mmx_psra_w:
00347   case Intrinsic::x86_mmx_psrl_d:
00348   case Intrinsic::x86_mmx_psrl_q:
00349   case Intrinsic::x86_mmx_psrl_w: {
00350     Value *Operands[2];
00351     
00352     Operands[0] = CI->getOperand(1);
00353     
00354     // Cast the second parameter to the correct type.
00355     BitCastInst *BC = new BitCastInst(CI->getOperand(2), 
00356                                       NewFn->getFunctionType()->getParamType(1),
00357                                       "upgraded.", CI);
00358     Operands[1] = BC;
00359     
00360     //  Construct a new CallInst
00361     CallInst *NewCI = CallInst::Create(NewFn, Operands, Operands+2, 
00362                                        "upgraded."+CI->getName(), CI);
00363     NewCI->setTailCall(CI->isTailCall());
00364     NewCI->setCallingConv(CI->getCallingConv());
00365     
00366     //  Handle any uses of the old CallInst.
00367     if (!CI->use_empty())
00368       //  Replace all uses of the old call with the new cast which has the 
00369       //  correct type.
00370       CI->replaceAllUsesWith(NewCI);
00371     
00372     //  Clean up the old call now that it has been completely upgraded.
00373     CI->eraseFromParent();
00374     break;
00375   }        
00376   case Intrinsic::ctlz:
00377   case Intrinsic::ctpop:
00378   case Intrinsic::cttz: {
00379     //  Build a small vector of the 1..(N-1) operands, which are the 
00380     //  parameters.
00381     SmallVector<Value*, 8> Operands(CI->op_begin()+1, CI->op_end());
00382 
00383     //  Construct a new CallInst
00384     CallInst *NewCI = CallInst::Create(NewFn, Operands.begin(), Operands.end(),
00385                                        "upgraded."+CI->getName(), CI);
00386     NewCI->setTailCall(CI->isTailCall());
00387     NewCI->setCallingConv(CI->getCallingConv());
00388 
00389     //  Handle any uses of the old CallInst.
00390     if (!CI->use_empty()) {
00391       //  Check for sign extend parameter attributes on the return values.
00392       bool SrcSExt = NewFn->getAttributes().paramHasAttr(0, Attribute::SExt);
00393       bool DestSExt = F->getAttributes().paramHasAttr(0, Attribute::SExt);
00394       
00395       //  Construct an appropriate cast from the new return type to the old.
00396       CastInst *RetCast = CastInst::Create(
00397                             CastInst::getCastOpcode(NewCI, SrcSExt,
00398                                                     F->getReturnType(),
00399                                                     DestSExt),
00400                             NewCI, F->getReturnType(),
00401                             NewCI->getName(), CI);
00402       NewCI->moveBefore(RetCast);
00403 
00404       //  Replace all uses of the old call with the new cast which has the 
00405       //  correct type.
00406       CI->replaceAllUsesWith(RetCast);
00407     }
00408 
00409     //  Clean up the old call now that it has been completely upgraded.
00410     CI->eraseFromParent();
00411   }
00412   break;
00413   }
00414 }
00415 
00416 // This tests each Function to determine if it needs upgrading. When we find 
00417 // one we are interested in, we then upgrade all calls to reflect the new 
00418 // function.
00419 void llvm::UpgradeCallsToIntrinsic(Function* F) {
00420   assert(F && "Illegal attempt to upgrade a non-existent intrinsic.");
00421 
00422   // Upgrade the function and check if it is a totaly new function.
00423   Function* NewFn;
00424   if (UpgradeIntrinsicFunction(F, NewFn)) {
00425     if (NewFn != F) {
00426       // Replace all uses to the old function with the new one if necessary.
00427       for (Value::use_iterator UI = F->use_begin(), UE = F->use_end();
00428            UI != UE; ) {
00429         if (CallInst* CI = dyn_cast<CallInst>(*UI++))
00430           UpgradeIntrinsicCall(CI, NewFn);
00431       }
00432       // Remove old function, no longer used, from the module.
00433       F->eraseFromParent();
00434     }
00435   }
00436 }