Eliminate x86.sse2.punpckh.qdq and x86.sse2.punpckl.qdq.
[oota-llvm.git] / lib / VMCore / AutoUpgrade.cpp
1 //===-- AutoUpgrade.cpp - Implement auto-upgrade helper functions ---------===//
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 //
10 // This file implements the auto-upgrade helper functions 
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/AutoUpgrade.h"
15 #include "llvm/Constants.h"
16 #include "llvm/Function.h"
17 #include "llvm/Module.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Intrinsics.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include <cstring>
22 using namespace llvm;
23
24
25 static bool UpgradeIntrinsicFunction1(Function *F, Function *&NewFn) {
26   assert(F && "Illegal to upgrade a non-existent Function.");
27
28   // Get the Function's name.
29   const std::string& Name = F->getName();
30
31   // Convenience
32   const FunctionType *FTy = F->getFunctionType();
33
34   // Quickly eliminate it, if it's not a candidate.
35   if (Name.length() <= 8 || Name[0] != 'l' || Name[1] != 'l' || 
36       Name[2] != 'v' || Name[3] != 'm' || Name[4] != '.')
37     return false;
38
39   Module *M = F->getParent();
40   switch (Name[5]) {
41   default: break;
42   case 'b':
43     //  This upgrades the name of the llvm.bswap intrinsic function to only use 
44     //  a single type name for overloading. We only care about the old format
45     //  'llvm.bswap.i*.i*', so check for 'bswap.' and then for there being 
46     //  a '.' after 'bswap.'
47     if (Name.compare(5,6,"bswap.",6) == 0) {
48       std::string::size_type delim = Name.find('.',11);
49       
50       if (delim != std::string::npos) {
51         //  Construct the new name as 'llvm.bswap' + '.i*'
52         F->setName(Name.substr(0,10)+Name.substr(delim));
53         NewFn = F;
54         return true;
55       }
56     }
57     break;
58
59   case 'c':
60     //  We only want to fix the 'llvm.ct*' intrinsics which do not have the 
61     //  correct return type, so we check for the name, and then check if the 
62     //  return type does not match the parameter type.
63     if ( (Name.compare(5,5,"ctpop",5) == 0 ||
64           Name.compare(5,4,"ctlz",4) == 0 ||
65           Name.compare(5,4,"cttz",4) == 0) &&
66         FTy->getReturnType() != FTy->getParamType(0)) {
67       //  We first need to change the name of the old (bad) intrinsic, because 
68       //  its type is incorrect, but we cannot overload that name. We 
69       //  arbitrarily unique it here allowing us to construct a correctly named 
70       //  and typed function below.
71       F->setName("");
72
73       //  Now construct the new intrinsic with the correct name and type. We 
74       //  leave the old function around in order to query its type, whatever it 
75       //  may be, and correctly convert up to the new type.
76       NewFn = cast<Function>(M->getOrInsertFunction(Name, 
77                                                     FTy->getParamType(0),
78                                                     FTy->getParamType(0),
79                                                     (Type *)0));
80       return true;
81     }
82     break;
83
84   case 'p':
85     //  This upgrades the llvm.part.select overloaded intrinsic names to only 
86     //  use one type specifier in the name. We only care about the old format
87     //  'llvm.part.select.i*.i*', and solve as above with bswap.
88     if (Name.compare(5,12,"part.select.",12) == 0) {
89       std::string::size_type delim = Name.find('.',17);
90       
91       if (delim != std::string::npos) {
92         //  Construct a new name as 'llvm.part.select' + '.i*'
93         F->setName(Name.substr(0,16)+Name.substr(delim));
94         NewFn = F;
95         return true;
96       }
97       break;
98     }
99
100     //  This upgrades the llvm.part.set intrinsics similarly as above, however 
101     //  we care about 'llvm.part.set.i*.i*.i*', but only the first two types 
102     //  must match. There is an additional type specifier after these two 
103     //  matching types that we must retain when upgrading.  Thus, we require 
104     //  finding 2 periods, not just one, after the intrinsic name.
105     if (Name.compare(5,9,"part.set.",9) == 0) {
106       std::string::size_type delim = Name.find('.',14);
107
108       if (delim != std::string::npos &&
109           Name.find('.',delim+1) != std::string::npos) {
110         //  Construct a new name as 'llvm.part.select' + '.i*.i*'
111         F->setName(Name.substr(0,13)+Name.substr(delim));
112         NewFn = F;
113         return true;
114       }
115       break;
116     }
117
118     break;
119   case 'x': 
120     // This fixes all MMX shift intrinsic instructions to take a
121     // v1i64 instead of a v2i32 as the second parameter.
122     if (Name.compare(5,10,"x86.mmx.ps",10) == 0 &&
123         (Name.compare(13,4,"psll", 4) == 0 ||
124          Name.compare(13,4,"psra", 4) == 0 ||
125          Name.compare(13,4,"psrl", 4) == 0) && Name[17] != 'i') {
126       
127       const llvm::Type *VT = VectorType::get(IntegerType::get(64), 1);
128       
129       // We don't have to do anything if the parameter already has
130       // the correct type.
131       if (FTy->getParamType(1) == VT)
132         break;
133       
134       //  We first need to change the name of the old (bad) intrinsic, because 
135       //  its type is incorrect, but we cannot overload that name. We 
136       //  arbitrarily unique it here allowing us to construct a correctly named 
137       //  and typed function below.
138       F->setName("");
139
140       assert(FTy->getNumParams() == 2 && "MMX shift intrinsics take 2 args!");
141       
142       //  Now construct the new intrinsic with the correct name and type. We 
143       //  leave the old function around in order to query its type, whatever it 
144       //  may be, and correctly convert up to the new type.
145       NewFn = cast<Function>(M->getOrInsertFunction(Name, 
146                                                     FTy->getReturnType(),
147                                                     FTy->getParamType(0),
148                                                     VT,
149                                                     (Type *)0));
150       return true;
151     } else if (Name.compare(5,17,"x86.sse2.loadh.pd",17) == 0 ||
152                Name.compare(5,17,"x86.sse2.loadl.pd",17) == 0 ||
153                Name.compare(5,16,"x86.sse2.movl.dq",16) == 0 ||
154                Name.compare(5,15,"x86.sse2.movs.d",15) == 0 ||
155                Name.compare(5,16,"x86.sse2.shuf.pd",16) == 0 ||
156                Name.compare(5,18,"x86.sse2.unpckh.pd",18) == 0 ||
157                Name.compare(5,18,"x86.sse2.unpckl.pd",18) == 0 ||
158                Name.compare(5,20,"x86.sse2.punpckh.qdq",20) == 0 ||
159                Name.compare(5,20,"x86.sse2.punpckl.qdq",20) == 0) {
160       // Calls to these intrinsics are transformed into ShuffleVector's.
161       NewFn = 0;
162       return true;
163     }
164
165     break;
166   }
167
168   //  This may not belong here. This function is effectively being overloaded 
169   //  to both detect an intrinsic which needs upgrading, and to provide the 
170   //  upgraded form of the intrinsic. We should perhaps have two separate 
171   //  functions for this.
172   return false;
173 }
174
175 bool llvm::UpgradeIntrinsicFunction(Function *F, Function *&NewFn) {
176   NewFn = 0;
177   bool Upgraded = UpgradeIntrinsicFunction1(F, NewFn);
178
179   // Upgrade intrinsic attributes.  This does not change the function.
180   if (NewFn)
181     F = NewFn;
182   if (unsigned id = F->getIntrinsicID(true))
183     F->setParamAttrs(Intrinsic::getParamAttrs((Intrinsic::ID)id));
184   return Upgraded;
185 }
186
187 // UpgradeIntrinsicCall - Upgrade a call to an old intrinsic to be a call the 
188 // upgraded intrinsic. All argument and return casting must be provided in 
189 // order to seamlessly integrate with existing context.
190 void llvm::UpgradeIntrinsicCall(CallInst *CI, Function *NewFn) {
191   Function *F = CI->getCalledFunction();
192   assert(F && "CallInst has no function associated with it.");
193
194   if (!NewFn) {
195     bool isLoadH = false, isLoadL = false, isMovL = false;
196     bool isMovSD = false, isShufPD = false;
197     bool isUnpckhPD = false, isUnpcklPD = false;
198     bool isPunpckhQPD = false, isPunpcklQPD = false;
199     if (strcmp(F->getNameStart(), "llvm.x86.sse2.loadh.pd") == 0)
200       isLoadH = true;
201     else if (strcmp(F->getNameStart(), "llvm.x86.sse2.loadl.pd") == 0)
202       isLoadL = true;
203     else if (strcmp(F->getNameStart(), "llvm.x86.sse2.movl.dq") == 0)
204       isMovL = true;
205     else if (strcmp(F->getNameStart(), "llvm.x86.sse2.movs.d") == 0)
206       isMovSD = true;
207     else if (strcmp(F->getNameStart(), "llvm.x86.sse2.shuf.pd") == 0)
208       isShufPD = true;
209     else if (strcmp(F->getNameStart(), "llvm.x86.sse2.unpckh.pd") == 0)
210       isUnpckhPD = true;
211     else if (strcmp(F->getNameStart(), "llvm.x86.sse2.unpckl.pd") == 0)
212       isUnpcklPD = true;
213     else if (strcmp(F->getNameStart(), "llvm.x86.sse2.punpckh.qdq") == 0)
214       isPunpckhQPD = true;
215     else if (strcmp(F->getNameStart(), "llvm.x86.sse2.punpckl.qdq") == 0)
216       isPunpcklQPD = true;
217
218     if (isLoadH || isLoadL || isMovL || isMovSD || isShufPD ||
219         isUnpckhPD || isUnpcklPD || isPunpckhQPD || isPunpcklQPD) {
220       std::vector<Constant*> Idxs;
221       Value *Op0 = CI->getOperand(1);
222       ShuffleVectorInst *SI = NULL;
223       if (isLoadH || isLoadL) {
224         Value *Op1 = UndefValue::get(Op0->getType());
225         Value *Addr = new BitCastInst(CI->getOperand(2), 
226                                       PointerType::getUnqual(Type::DoubleTy),
227                                       "upgraded.", CI);
228         Value *Load = new LoadInst(Addr, "upgraded.", false, 8, CI);
229         Value *Idx = ConstantInt::get(Type::Int32Ty, 0);
230         Op1 = InsertElementInst::Create(Op1, Load, Idx, "upgraded.", CI);
231
232         if (isLoadH) {
233           Idxs.push_back(ConstantInt::get(Type::Int32Ty, 0));
234           Idxs.push_back(ConstantInt::get(Type::Int32Ty, 2));
235         } else {
236           Idxs.push_back(ConstantInt::get(Type::Int32Ty, 2));
237           Idxs.push_back(ConstantInt::get(Type::Int32Ty, 1));
238         }
239         Value *Mask = ConstantVector::get(Idxs);
240         SI = new ShuffleVectorInst(Op0, Op1, Mask, "upgraded.", CI);
241       } else if (isMovL) {
242         Constant *Zero = ConstantInt::get(Type::Int32Ty, 0);
243         Idxs.push_back(Zero);
244         Idxs.push_back(Zero);
245         Idxs.push_back(Zero);
246         Idxs.push_back(Zero);
247         Value *ZeroV = ConstantVector::get(Idxs);
248
249         Idxs.clear(); 
250         Idxs.push_back(ConstantInt::get(Type::Int32Ty, 4));
251         Idxs.push_back(ConstantInt::get(Type::Int32Ty, 5));
252         Idxs.push_back(ConstantInt::get(Type::Int32Ty, 2));
253         Idxs.push_back(ConstantInt::get(Type::Int32Ty, 3));
254         Value *Mask = ConstantVector::get(Idxs);
255         SI = new ShuffleVectorInst(ZeroV, Op0, Mask, "upgraded.", CI);
256       } else if (isMovSD ||
257                  isUnpckhPD || isUnpcklPD || isPunpckhQPD || isPunpcklQPD) {
258         Value *Op1 = CI->getOperand(2);
259         if (isMovSD) {
260           Idxs.push_back(ConstantInt::get(Type::Int32Ty, 2));
261           Idxs.push_back(ConstantInt::get(Type::Int32Ty, 1));
262         } else if (isUnpckhPD || isPunpckhQPD) {
263           Idxs.push_back(ConstantInt::get(Type::Int32Ty, 1));
264           Idxs.push_back(ConstantInt::get(Type::Int32Ty, 3));
265         } else {
266           Idxs.push_back(ConstantInt::get(Type::Int32Ty, 0));
267           Idxs.push_back(ConstantInt::get(Type::Int32Ty, 2));
268         }
269         Value *Mask = ConstantVector::get(Idxs);
270         SI = new ShuffleVectorInst(Op0, Op1, Mask, "upgraded.", CI);
271       } else if (isShufPD) {
272         Value *Op1 = CI->getOperand(2);
273         unsigned MaskVal = cast<ConstantInt>(CI->getOperand(3))->getZExtValue();
274         Idxs.push_back(ConstantInt::get(Type::Int32Ty, MaskVal & 1));
275         Idxs.push_back(ConstantInt::get(Type::Int32Ty, ((MaskVal >> 1) & 1)+2));
276         Value *Mask = ConstantVector::get(Idxs);
277         SI = new ShuffleVectorInst(Op0, Op1, Mask, "upgraded.", CI);
278       }
279
280       assert(SI && "Unexpected!");
281
282       // Handle any uses of the old CallInst.
283       if (!CI->use_empty())
284         //  Replace all uses of the old call with the new cast which has the 
285         //  correct type.
286         CI->replaceAllUsesWith(SI);
287       
288       //  Clean up the old call now that it has been completely upgraded.
289       CI->eraseFromParent();
290     } else {
291       assert(0 && "Unknown function for CallInst upgrade.");
292     }
293     return;
294   }
295
296   switch (NewFn->getIntrinsicID()) {
297   default:  assert(0 && "Unknown function for CallInst upgrade.");
298   case Intrinsic::x86_mmx_psll_d:
299   case Intrinsic::x86_mmx_psll_q:
300   case Intrinsic::x86_mmx_psll_w:
301   case Intrinsic::x86_mmx_psra_d:
302   case Intrinsic::x86_mmx_psra_w:
303   case Intrinsic::x86_mmx_psrl_d:
304   case Intrinsic::x86_mmx_psrl_q:
305   case Intrinsic::x86_mmx_psrl_w: {
306     Value *Operands[2];
307     
308     Operands[0] = CI->getOperand(1);
309     
310     // Cast the second parameter to the correct type.
311     BitCastInst *BC = new BitCastInst(CI->getOperand(2), 
312                                       NewFn->getFunctionType()->getParamType(1),
313                                       "upgraded.", CI);
314     Operands[1] = BC;
315     
316     //  Construct a new CallInst
317     CallInst *NewCI = CallInst::Create(NewFn, Operands, Operands+2, 
318                                        "upgraded."+CI->getName(), CI);
319     NewCI->setTailCall(CI->isTailCall());
320     NewCI->setCallingConv(CI->getCallingConv());
321     
322     //  Handle any uses of the old CallInst.
323     if (!CI->use_empty())
324       //  Replace all uses of the old call with the new cast which has the 
325       //  correct type.
326       CI->replaceAllUsesWith(NewCI);
327     
328     //  Clean up the old call now that it has been completely upgraded.
329     CI->eraseFromParent();
330     break;
331   }        
332   case Intrinsic::ctlz:
333   case Intrinsic::ctpop:
334   case Intrinsic::cttz: {
335     //  Build a small vector of the 1..(N-1) operands, which are the 
336     //  parameters.
337     SmallVector<Value*, 8> Operands(CI->op_begin()+1, CI->op_end());
338
339     //  Construct a new CallInst
340     CallInst *NewCI = CallInst::Create(NewFn, Operands.begin(), Operands.end(),
341                                        "upgraded."+CI->getName(), CI);
342     NewCI->setTailCall(CI->isTailCall());
343     NewCI->setCallingConv(CI->getCallingConv());
344
345     //  Handle any uses of the old CallInst.
346     if (!CI->use_empty()) {
347       //  Check for sign extend parameter attributes on the return values.
348       bool SrcSExt = NewFn->getParamAttrs().paramHasAttr(0, ParamAttr::SExt);
349       bool DestSExt = F->getParamAttrs().paramHasAttr(0, ParamAttr::SExt);
350       
351       //  Construct an appropriate cast from the new return type to the old.
352       CastInst *RetCast = CastInst::Create(
353                             CastInst::getCastOpcode(NewCI, SrcSExt,
354                                                     F->getReturnType(),
355                                                     DestSExt),
356                             NewCI, F->getReturnType(),
357                             NewCI->getName(), CI);
358       NewCI->moveBefore(RetCast);
359
360       //  Replace all uses of the old call with the new cast which has the 
361       //  correct type.
362       CI->replaceAllUsesWith(RetCast);
363     }
364
365     //  Clean up the old call now that it has been completely upgraded.
366     CI->eraseFromParent();
367   }
368   break;
369   }
370 }
371
372 // This tests each Function to determine if it needs upgrading. When we find 
373 // one we are interested in, we then upgrade all calls to reflect the new 
374 // function.
375 void llvm::UpgradeCallsToIntrinsic(Function* F) {
376   assert(F && "Illegal attempt to upgrade a non-existent intrinsic.");
377
378   // Upgrade the function and check if it is a totaly new function.
379   Function* NewFn;
380   if (UpgradeIntrinsicFunction(F, NewFn)) {
381     if (NewFn != F) {
382       // Replace all uses to the old function with the new one if necessary.
383       for (Value::use_iterator UI = F->use_begin(), UE = F->use_end();
384            UI != UE; ) {
385         if (CallInst* CI = dyn_cast<CallInst>(*UI++))
386           UpgradeIntrinsicCall(CI, NewFn);
387       }
388       // Remove old function, no longer used, from the module.
389       F->eraseFromParent();
390     }
391   }
392 }
393