[x86] Change AVX512 intrinsics to take a 8-bit immediate for the comparision kind...
[oota-llvm.git] / lib / IR / 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/IR/AutoUpgrade.h"
15 #include "llvm/IR/CFG.h"
16 #include "llvm/IR/CallSite.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/DIBuilder.h"
19 #include "llvm/IR/DebugInfo.h"
20 #include "llvm/IR/DiagnosticInfo.h"
21 #include "llvm/IR/Function.h"
22 #include "llvm/IR/IRBuilder.h"
23 #include "llvm/IR/Instruction.h"
24 #include "llvm/IR/IntrinsicInst.h"
25 #include "llvm/IR/LLVMContext.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include <cstring>
29 using namespace llvm;
30
31 // Upgrade the declarations of the SSE4.1 functions whose arguments have
32 // changed their type from v4f32 to v2i64.
33 static bool UpgradeSSE41Function(Function* F, Intrinsic::ID IID,
34                                  Function *&NewFn) {
35   // Check whether this is an old version of the function, which received
36   // v4f32 arguments.
37   Type *Arg0Type = F->getFunctionType()->getParamType(0);
38   if (Arg0Type != VectorType::get(Type::getFloatTy(F->getContext()), 4))
39     return false;
40
41   // Yes, it's old, replace it with new version.
42   F->setName(F->getName() + ".old");
43   NewFn = Intrinsic::getDeclaration(F->getParent(), IID);
44   return true;
45 }
46
47 // Upgrade the declarations of intrinsic functions whose 8-bit immediate mask
48 // arguments have changed their type from i32 to i8.
49 static bool UpgradeX86IntrinsicsWith8BitMask(Function *F, Intrinsic::ID IID,
50                                              Function *&NewFn) {
51   // Check that the last argument is an i32.
52   Type *LastArgType = F->getFunctionType()->getParamType(
53      F->getFunctionType()->getNumParams() - 1);
54   if (!LastArgType->isIntegerTy(32))
55     return false;
56
57   // Move this function aside and map down.
58   F->setName(F->getName() + ".old");
59   NewFn = Intrinsic::getDeclaration(F->getParent(), IID);
60   return true;
61 }
62
63 // Upgrade the declarations of AVX-512 cmp intrinsic functions whose 8-bit
64 // immediates have changed their type from i32 to i8.
65 static bool UpgradeAVX512CmpIntrinsic(Function *F, Intrinsic::ID IID,
66                                       Function *&NewFn) {
67   // Check that the last argument is an i32.
68   Type *LastArgType = F->getFunctionType()->getParamType(2);
69   if (!LastArgType->isIntegerTy(32))
70     return false;
71
72   // Move this function aside and map down.
73   F->setName(F->getName() + ".old");
74   NewFn = Intrinsic::getDeclaration(F->getParent(), IID);
75   return true;
76 }
77
78 static bool UpgradeIntrinsicFunction1(Function *F, Function *&NewFn) {
79   assert(F && "Illegal to upgrade a non-existent Function.");
80
81   // Quickly eliminate it, if it's not a candidate.
82   StringRef Name = F->getName();
83   if (Name.size() <= 8 || !Name.startswith("llvm."))
84     return false;
85   Name = Name.substr(5); // Strip off "llvm."
86
87   switch (Name[0]) {
88   default: break;
89   case 'a': {
90     if (Name.startswith("arm.neon.vclz")) {
91       Type* args[2] = {
92         F->arg_begin()->getType(),
93         Type::getInt1Ty(F->getContext())
94       };
95       // Can't use Intrinsic::getDeclaration here as it adds a ".i1" to
96       // the end of the name. Change name from llvm.arm.neon.vclz.* to
97       //  llvm.ctlz.*
98       FunctionType* fType = FunctionType::get(F->getReturnType(), args, false);
99       NewFn = Function::Create(fType, F->getLinkage(),
100                                "llvm.ctlz." + Name.substr(14), F->getParent());
101       return true;
102     }
103     if (Name.startswith("arm.neon.vcnt")) {
104       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctpop,
105                                         F->arg_begin()->getType());
106       return true;
107     }
108     break;
109   }
110   case 'c': {
111     if (Name.startswith("ctlz.") && F->arg_size() == 1) {
112       F->setName(Name + ".old");
113       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctlz,
114                                         F->arg_begin()->getType());
115       return true;
116     }
117     if (Name.startswith("cttz.") && F->arg_size() == 1) {
118       F->setName(Name + ".old");
119       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::cttz,
120                                         F->arg_begin()->getType());
121       return true;
122     }
123     break;
124   }
125   case 'd': {
126     if (Name.startswith("dbg.declare") && F->arg_size() == 2) {
127       F->setName(Name + ".old");
128       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::dbg_declare);
129       return true;
130     }
131     if (Name.startswith("dbg.value") && F->arg_size() == 3) {
132       F->setName(Name + ".old");
133       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::dbg_value);
134       return true;
135     }
136     break;
137   }
138
139   case 'o':
140     // We only need to change the name to match the mangling including the
141     // address space.
142     if (F->arg_size() == 2 && Name.startswith("objectsize.")) {
143       Type *Tys[2] = { F->getReturnType(), F->arg_begin()->getType() };
144       if (F->getName() != Intrinsic::getName(Intrinsic::objectsize, Tys)) {
145         F->setName(Name + ".old");
146         NewFn = Intrinsic::getDeclaration(F->getParent(),
147                                           Intrinsic::objectsize, Tys);
148         return true;
149       }
150     }
151     break;
152
153   case 'x': {
154     if (Name.startswith("x86.sse2.pcmpeq.") ||
155         Name.startswith("x86.sse2.pcmpgt.") ||
156         Name.startswith("x86.avx2.pcmpeq.") ||
157         Name.startswith("x86.avx2.pcmpgt.") ||
158         Name.startswith("x86.avx.vpermil.") ||
159         Name == "x86.avx.movnt.dq.256" ||
160         Name == "x86.avx.movnt.pd.256" ||
161         Name == "x86.avx.movnt.ps.256" ||
162         Name == "x86.sse42.crc32.64.8" ||
163         Name == "x86.avx.vbroadcast.ss" ||
164         Name == "x86.avx.vbroadcast.ss.256" ||
165         Name == "x86.avx.vbroadcast.sd.256" ||
166         (Name.startswith("x86.xop.vpcom") && F->arg_size() == 2)) {
167       NewFn = nullptr;
168       return true;
169     }
170     // SSE4.1 ptest functions may have an old signature.
171     if (Name.startswith("x86.sse41.ptest")) {
172       if (Name == "x86.sse41.ptestc")
173         return UpgradeSSE41Function(F, Intrinsic::x86_sse41_ptestc, NewFn);
174       if (Name == "x86.sse41.ptestz")
175         return UpgradeSSE41Function(F, Intrinsic::x86_sse41_ptestz, NewFn);
176       if (Name == "x86.sse41.ptestnzc")
177         return UpgradeSSE41Function(F, Intrinsic::x86_sse41_ptestnzc, NewFn);
178     }
179     // Several blend and other instructions with maskes used the wrong number of
180     // bits.
181     if (Name == "x86.sse41.pblendw")
182       return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_pblendw,
183                                               NewFn);
184     if (Name == "x86.sse41.blendpd")
185       return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_blendpd,
186                                               NewFn);
187     if (Name == "x86.sse41.blendps")
188       return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_blendps,
189                                               NewFn);
190     if (Name == "x86.sse41.insertps")
191       return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_insertps,
192                                               NewFn);
193     if (Name == "x86.sse41.dppd")
194       return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_dppd,
195                                               NewFn);
196     if (Name == "x86.sse41.dpps")
197       return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_dpps,
198                                               NewFn);
199     if (Name == "x86.sse41.mpsadbw")
200       return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_mpsadbw,
201                                               NewFn);
202     if (Name == "x86.avx.blend.pd.256")
203       return UpgradeX86IntrinsicsWith8BitMask(
204           F, Intrinsic::x86_avx_blend_pd_256, NewFn);
205     if (Name == "x86.avx.blend.ps.256")
206       return UpgradeX86IntrinsicsWith8BitMask(
207           F, Intrinsic::x86_avx_blend_ps_256, NewFn);
208     if (Name == "x86.avx.dp.ps.256")
209       return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_avx_dp_ps_256,
210                                               NewFn);
211     if (Name == "x86.avx2.pblendw")
212       return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_avx2_pblendw,
213                                               NewFn);
214     if (Name == "x86.avx2.pblendd.128")
215       return UpgradeX86IntrinsicsWith8BitMask(
216           F, Intrinsic::x86_avx2_pblendd_128, NewFn);
217     if (Name == "x86.avx2.pblendd.256")
218       return UpgradeX86IntrinsicsWith8BitMask(
219           F, Intrinsic::x86_avx2_pblendd_256, NewFn);
220     if (Name == "x86.avx2.mpsadbw")
221       return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_avx2_mpsadbw,
222                                               NewFn);
223
224     if (Name == "x86.avx512.mask.cmp.ps.512")
225       return UpgradeAVX512CmpIntrinsic(F, Intrinsic::x86_avx512_mask_cmp_ps_512,
226                                        NewFn);
227     if (Name == "x86.avx512.mask.cmp.pd.512")
228       return UpgradeAVX512CmpIntrinsic(F, Intrinsic::x86_avx512_mask_cmp_pd_512,
229                                        NewFn);
230
231     // frcz.ss/sd may need to have an argument dropped
232     if (Name.startswith("x86.xop.vfrcz.ss") && F->arg_size() == 2) {
233       F->setName(Name + ".old");
234       NewFn = Intrinsic::getDeclaration(F->getParent(),
235                                         Intrinsic::x86_xop_vfrcz_ss);
236       return true;
237     }
238     if (Name.startswith("x86.xop.vfrcz.sd") && F->arg_size() == 2) {
239       F->setName(Name + ".old");
240       NewFn = Intrinsic::getDeclaration(F->getParent(),
241                                         Intrinsic::x86_xop_vfrcz_sd);
242       return true;
243     }
244     // Fix the FMA4 intrinsics to remove the 4
245     if (Name.startswith("x86.fma4.")) {
246       F->setName("llvm.x86.fma" + Name.substr(8));
247       NewFn = F;
248       return true;
249     }
250     break;
251   }
252   }
253
254   //  This may not belong here. This function is effectively being overloaded
255   //  to both detect an intrinsic which needs upgrading, and to provide the
256   //  upgraded form of the intrinsic. We should perhaps have two separate
257   //  functions for this.
258   return false;
259 }
260
261 bool llvm::UpgradeIntrinsicFunction(Function *F, Function *&NewFn) {
262   NewFn = nullptr;
263   bool Upgraded = UpgradeIntrinsicFunction1(F, NewFn);
264
265   // Upgrade intrinsic attributes.  This does not change the function.
266   if (NewFn)
267     F = NewFn;
268   if (unsigned id = F->getIntrinsicID())
269     F->setAttributes(Intrinsic::getAttributes(F->getContext(),
270                                               (Intrinsic::ID)id));
271   return Upgraded;
272 }
273
274 bool llvm::UpgradeGlobalVariable(GlobalVariable *GV) {
275   // Nothing to do yet.
276   return false;
277 }
278
279 static MDNode *getNodeField(const MDNode *DbgNode, unsigned Elt) {
280   if (!DbgNode || Elt >= DbgNode->getNumOperands())
281     return nullptr;
282   return dyn_cast_or_null<MDNode>(DbgNode->getOperand(Elt));
283 }
284
285 static MetadataAsValue *getExpression(Value *VarOperand, Function *F) {
286   // Old-style DIVariables have an optional expression as the 8th element.
287   DIExpression Expr(getNodeField(
288       cast<MDNode>(cast<MetadataAsValue>(VarOperand)->getMetadata()), 8));
289   if (!Expr) {
290     DIBuilder DIB(*F->getParent(), /*AllowUnresolved*/ false);
291     Expr = DIB.createExpression();
292   }
293   return MetadataAsValue::get(F->getContext(), Expr);
294 }
295
296 // UpgradeIntrinsicCall - Upgrade a call to an old intrinsic to be a call the
297 // upgraded intrinsic. All argument and return casting must be provided in
298 // order to seamlessly integrate with existing context.
299 void llvm::UpgradeIntrinsicCall(CallInst *CI, Function *NewFn) {
300   Function *F = CI->getCalledFunction();
301   LLVMContext &C = CI->getContext();
302   IRBuilder<> Builder(C);
303   Builder.SetInsertPoint(CI->getParent(), CI);
304
305   assert(F && "Intrinsic call is not direct?");
306
307   if (!NewFn) {
308     // Get the Function's name.
309     StringRef Name = F->getName();
310
311     Value *Rep;
312     // Upgrade packed integer vector compares intrinsics to compare instructions
313     if (Name.startswith("llvm.x86.sse2.pcmpeq.") ||
314         Name.startswith("llvm.x86.avx2.pcmpeq.")) {
315       Rep = Builder.CreateICmpEQ(CI->getArgOperand(0), CI->getArgOperand(1),
316                                  "pcmpeq");
317       // need to sign extend since icmp returns vector of i1
318       Rep = Builder.CreateSExt(Rep, CI->getType(), "");
319     } else if (Name.startswith("llvm.x86.sse2.pcmpgt.") ||
320                Name.startswith("llvm.x86.avx2.pcmpgt.")) {
321       Rep = Builder.CreateICmpSGT(CI->getArgOperand(0), CI->getArgOperand(1),
322                                   "pcmpgt");
323       // need to sign extend since icmp returns vector of i1
324       Rep = Builder.CreateSExt(Rep, CI->getType(), "");
325     } else if (Name == "llvm.x86.avx.movnt.dq.256" ||
326                Name == "llvm.x86.avx.movnt.ps.256" ||
327                Name == "llvm.x86.avx.movnt.pd.256") {
328       IRBuilder<> Builder(C);
329       Builder.SetInsertPoint(CI->getParent(), CI);
330
331       Module *M = F->getParent();
332       SmallVector<Metadata *, 1> Elts;
333       Elts.push_back(
334           ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(C), 1)));
335       MDNode *Node = MDNode::get(C, Elts);
336
337       Value *Arg0 = CI->getArgOperand(0);
338       Value *Arg1 = CI->getArgOperand(1);
339
340       // Convert the type of the pointer to a pointer to the stored type.
341       Value *BC = Builder.CreateBitCast(Arg0,
342                                         PointerType::getUnqual(Arg1->getType()),
343                                         "cast");
344       StoreInst *SI = Builder.CreateStore(Arg1, BC);
345       SI->setMetadata(M->getMDKindID("nontemporal"), Node);
346       SI->setAlignment(16);
347
348       // Remove intrinsic.
349       CI->eraseFromParent();
350       return;
351     } else if (Name.startswith("llvm.x86.xop.vpcom")) {
352       Intrinsic::ID intID;
353       if (Name.endswith("ub"))
354         intID = Intrinsic::x86_xop_vpcomub;
355       else if (Name.endswith("uw"))
356         intID = Intrinsic::x86_xop_vpcomuw;
357       else if (Name.endswith("ud"))
358         intID = Intrinsic::x86_xop_vpcomud;
359       else if (Name.endswith("uq"))
360         intID = Intrinsic::x86_xop_vpcomuq;
361       else if (Name.endswith("b"))
362         intID = Intrinsic::x86_xop_vpcomb;
363       else if (Name.endswith("w"))
364         intID = Intrinsic::x86_xop_vpcomw;
365       else if (Name.endswith("d"))
366         intID = Intrinsic::x86_xop_vpcomd;
367       else if (Name.endswith("q"))
368         intID = Intrinsic::x86_xop_vpcomq;
369       else
370         llvm_unreachable("Unknown suffix");
371
372       Name = Name.substr(18); // strip off "llvm.x86.xop.vpcom"
373       unsigned Imm;
374       if (Name.startswith("lt"))
375         Imm = 0;
376       else if (Name.startswith("le"))
377         Imm = 1;
378       else if (Name.startswith("gt"))
379         Imm = 2;
380       else if (Name.startswith("ge"))
381         Imm = 3;
382       else if (Name.startswith("eq"))
383         Imm = 4;
384       else if (Name.startswith("ne"))
385         Imm = 5;
386       else if (Name.startswith("true"))
387         Imm = 6;
388       else if (Name.startswith("false"))
389         Imm = 7;
390       else
391         llvm_unreachable("Unknown condition");
392
393       Function *VPCOM = Intrinsic::getDeclaration(F->getParent(), intID);
394       Rep = Builder.CreateCall3(VPCOM, CI->getArgOperand(0),
395                                 CI->getArgOperand(1), Builder.getInt8(Imm));
396     } else if (Name == "llvm.x86.sse42.crc32.64.8") {
397       Function *CRC32 = Intrinsic::getDeclaration(F->getParent(),
398                                                Intrinsic::x86_sse42_crc32_32_8);
399       Value *Trunc0 = Builder.CreateTrunc(CI->getArgOperand(0), Type::getInt32Ty(C));
400       Rep = Builder.CreateCall2(CRC32, Trunc0, CI->getArgOperand(1));
401       Rep = Builder.CreateZExt(Rep, CI->getType(), "");
402     } else if (Name.startswith("llvm.x86.avx.vbroadcast")) {
403       // Replace broadcasts with a series of insertelements.
404       Type *VecTy = CI->getType();
405       Type *EltTy = VecTy->getVectorElementType();
406       unsigned EltNum = VecTy->getVectorNumElements();
407       Value *Cast = Builder.CreateBitCast(CI->getArgOperand(0),
408                                           EltTy->getPointerTo());
409       Value *Load = Builder.CreateLoad(Cast);
410       Type *I32Ty = Type::getInt32Ty(C);
411       Rep = UndefValue::get(VecTy);
412       for (unsigned I = 0; I < EltNum; ++I)
413         Rep = Builder.CreateInsertElement(Rep, Load,
414                                           ConstantInt::get(I32Ty, I));
415     } else {
416       bool PD128 = false, PD256 = false, PS128 = false, PS256 = false;
417       if (Name == "llvm.x86.avx.vpermil.pd.256")
418         PD256 = true;
419       else if (Name == "llvm.x86.avx.vpermil.pd")
420         PD128 = true;
421       else if (Name == "llvm.x86.avx.vpermil.ps.256")
422         PS256 = true;
423       else if (Name == "llvm.x86.avx.vpermil.ps")
424         PS128 = true;
425
426       if (PD256 || PD128 || PS256 || PS128) {
427         Value *Op0 = CI->getArgOperand(0);
428         unsigned Imm = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
429         SmallVector<Constant*, 8> Idxs;
430
431         if (PD128)
432           for (unsigned i = 0; i != 2; ++i)
433             Idxs.push_back(Builder.getInt32((Imm >> i) & 0x1));
434         else if (PD256)
435           for (unsigned l = 0; l != 4; l+=2)
436             for (unsigned i = 0; i != 2; ++i)
437               Idxs.push_back(Builder.getInt32(((Imm >> (l+i)) & 0x1) + l));
438         else if (PS128)
439           for (unsigned i = 0; i != 4; ++i)
440             Idxs.push_back(Builder.getInt32((Imm >> (2 * i)) & 0x3));
441         else if (PS256)
442           for (unsigned l = 0; l != 8; l+=4)
443             for (unsigned i = 0; i != 4; ++i)
444               Idxs.push_back(Builder.getInt32(((Imm >> (2 * i)) & 0x3) + l));
445         else
446           llvm_unreachable("Unexpected function");
447
448         Rep = Builder.CreateShuffleVector(Op0, Op0, ConstantVector::get(Idxs));
449       } else {
450         llvm_unreachable("Unknown function for CallInst upgrade.");
451       }
452     }
453
454     CI->replaceAllUsesWith(Rep);
455     CI->eraseFromParent();
456     return;
457   }
458
459   std::string Name = CI->getName().str();
460   if (!Name.empty())
461     CI->setName(Name + ".old");
462
463   switch (NewFn->getIntrinsicID()) {
464   default:
465     llvm_unreachable("Unknown function for CallInst upgrade.");
466
467   // Upgrade debug intrinsics to use an additional DIExpression argument.
468   case Intrinsic::dbg_declare: {
469     auto NewCI =
470         Builder.CreateCall3(NewFn, CI->getArgOperand(0), CI->getArgOperand(1),
471                             getExpression(CI->getArgOperand(1), F), Name);
472     NewCI->setDebugLoc(CI->getDebugLoc());
473     CI->replaceAllUsesWith(NewCI);
474     CI->eraseFromParent();
475     return;
476   }
477   case Intrinsic::dbg_value: {
478     auto NewCI = Builder.CreateCall4(
479         NewFn, CI->getArgOperand(0), CI->getArgOperand(1), CI->getArgOperand(2),
480         getExpression(CI->getArgOperand(2), F), Name);
481     NewCI->setDebugLoc(CI->getDebugLoc());
482     CI->replaceAllUsesWith(NewCI);
483     CI->eraseFromParent();
484     return;
485   }
486   case Intrinsic::ctlz:
487   case Intrinsic::cttz:
488     assert(CI->getNumArgOperands() == 1 &&
489            "Mismatch between function args and call args");
490     CI->replaceAllUsesWith(Builder.CreateCall2(NewFn, CI->getArgOperand(0),
491                                                Builder.getFalse(), Name));
492     CI->eraseFromParent();
493     return;
494
495   case Intrinsic::objectsize:
496     CI->replaceAllUsesWith(Builder.CreateCall2(NewFn,
497                                                CI->getArgOperand(0),
498                                                CI->getArgOperand(1),
499                                                Name));
500     CI->eraseFromParent();
501     return;
502
503   case Intrinsic::ctpop: {
504     CI->replaceAllUsesWith(Builder.CreateCall(NewFn, CI->getArgOperand(0)));
505     CI->eraseFromParent();
506     return;
507   }
508
509   case Intrinsic::x86_xop_vfrcz_ss:
510   case Intrinsic::x86_xop_vfrcz_sd:
511     CI->replaceAllUsesWith(Builder.CreateCall(NewFn, CI->getArgOperand(1),
512                                               Name));
513     CI->eraseFromParent();
514     return;
515
516   case Intrinsic::x86_sse41_ptestc:
517   case Intrinsic::x86_sse41_ptestz:
518   case Intrinsic::x86_sse41_ptestnzc: {
519     // The arguments for these intrinsics used to be v4f32, and changed
520     // to v2i64. This is purely a nop, since those are bitwise intrinsics.
521     // So, the only thing required is a bitcast for both arguments.
522     // First, check the arguments have the old type.
523     Value *Arg0 = CI->getArgOperand(0);
524     if (Arg0->getType() != VectorType::get(Type::getFloatTy(C), 4))
525       return;
526
527     // Old intrinsic, add bitcasts
528     Value *Arg1 = CI->getArgOperand(1);
529
530     Value *BC0 =
531       Builder.CreateBitCast(Arg0,
532                             VectorType::get(Type::getInt64Ty(C), 2),
533                             "cast");
534     Value *BC1 =
535       Builder.CreateBitCast(Arg1,
536                             VectorType::get(Type::getInt64Ty(C), 2),
537                             "cast");
538
539     CallInst* NewCall = Builder.CreateCall2(NewFn, BC0, BC1, Name);
540     CI->replaceAllUsesWith(NewCall);
541     CI->eraseFromParent();
542     return;
543   }
544
545   case Intrinsic::x86_sse41_pblendw:
546   case Intrinsic::x86_sse41_blendpd:
547   case Intrinsic::x86_sse41_blendps:
548   case Intrinsic::x86_sse41_insertps:
549   case Intrinsic::x86_sse41_dppd:
550   case Intrinsic::x86_sse41_dpps:
551   case Intrinsic::x86_sse41_mpsadbw:
552   case Intrinsic::x86_avx_blend_pd_256:
553   case Intrinsic::x86_avx_blend_ps_256:
554   case Intrinsic::x86_avx_dp_ps_256:
555   case Intrinsic::x86_avx2_pblendw:
556   case Intrinsic::x86_avx2_pblendd_128:
557   case Intrinsic::x86_avx2_pblendd_256:
558   case Intrinsic::x86_avx2_mpsadbw: {
559     // Need to truncate the last argument from i32 to i8 -- this argument models
560     // an inherently 8-bit immediate operand to these x86 instructions.
561     SmallVector<Value *, 4> Args(CI->arg_operands().begin(),
562                                  CI->arg_operands().end());
563
564     // Replace the last argument with a trunc.
565     Args.back() = Builder.CreateTrunc(Args.back(), Type::getInt8Ty(C), "trunc");
566
567     CallInst *NewCall = Builder.CreateCall(NewFn, Args);
568     CI->replaceAllUsesWith(NewCall);
569     CI->eraseFromParent();
570     return;
571   }
572   case Intrinsic::x86_avx512_mask_cmp_ps_512:
573   case Intrinsic::x86_avx512_mask_cmp_pd_512: {
574     // Need to truncate the last argument from i32 to i8 -- this argument models
575     // an inherently 8-bit immediate operand to these x86 instructions.
576     SmallVector<Value *, 5> Args(CI->arg_operands().begin(),
577                                  CI->arg_operands().end());
578
579     // Replace the last argument with a trunc.
580     Args[2] = Builder.CreateTrunc(Args[2], Type::getInt8Ty(C), "trunc");
581
582     CallInst *NewCall = Builder.CreateCall(NewFn, Args);
583     CI->replaceAllUsesWith(NewCall);
584     CI->eraseFromParent();
585     return;
586   }
587   }
588 }
589
590 // This tests each Function to determine if it needs upgrading. When we find
591 // one we are interested in, we then upgrade all calls to reflect the new
592 // function.
593 void llvm::UpgradeCallsToIntrinsic(Function* F) {
594   assert(F && "Illegal attempt to upgrade a non-existent intrinsic.");
595
596   // Upgrade the function and check if it is a totaly new function.
597   Function *NewFn;
598   if (UpgradeIntrinsicFunction(F, NewFn)) {
599     if (NewFn != F) {
600       // Replace all uses to the old function with the new one if necessary.
601       for (Value::user_iterator UI = F->user_begin(), UE = F->user_end();
602            UI != UE; ) {
603         if (CallInst *CI = dyn_cast<CallInst>(*UI++))
604           UpgradeIntrinsicCall(CI, NewFn);
605       }
606       // Remove old function, no longer used, from the module.
607       F->eraseFromParent();
608     }
609   }
610 }
611
612 void llvm::UpgradeInstWithTBAATag(Instruction *I) {
613   MDNode *MD = I->getMetadata(LLVMContext::MD_tbaa);
614   assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
615   // Check if the tag uses struct-path aware TBAA format.
616   if (isa<MDNode>(MD->getOperand(0)) && MD->getNumOperands() >= 3)
617     return;
618
619   if (MD->getNumOperands() == 3) {
620     Metadata *Elts[] = {MD->getOperand(0), MD->getOperand(1)};
621     MDNode *ScalarType = MDNode::get(I->getContext(), Elts);
622     // Create a MDNode <ScalarType, ScalarType, offset 0, const>
623     Metadata *Elts2[] = {ScalarType, ScalarType,
624                          ConstantAsMetadata::get(Constant::getNullValue(
625                              Type::getInt64Ty(I->getContext()))),
626                          MD->getOperand(2)};
627     I->setMetadata(LLVMContext::MD_tbaa, MDNode::get(I->getContext(), Elts2));
628   } else {
629     // Create a MDNode <MD, MD, offset 0>
630     Metadata *Elts[] = {MD, MD, ConstantAsMetadata::get(Constant::getNullValue(
631                                     Type::getInt64Ty(I->getContext())))};
632     I->setMetadata(LLVMContext::MD_tbaa, MDNode::get(I->getContext(), Elts));
633   }
634 }
635
636 Instruction *llvm::UpgradeBitCastInst(unsigned Opc, Value *V, Type *DestTy,
637                                       Instruction *&Temp) {
638   if (Opc != Instruction::BitCast)
639     return nullptr;
640
641   Temp = nullptr;
642   Type *SrcTy = V->getType();
643   if (SrcTy->isPtrOrPtrVectorTy() && DestTy->isPtrOrPtrVectorTy() &&
644       SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace()) {
645     LLVMContext &Context = V->getContext();
646
647     // We have no information about target data layout, so we assume that
648     // the maximum pointer size is 64bit.
649     Type *MidTy = Type::getInt64Ty(Context);
650     Temp = CastInst::Create(Instruction::PtrToInt, V, MidTy);
651
652     return CastInst::Create(Instruction::IntToPtr, Temp, DestTy);
653   }
654
655   return nullptr;
656 }
657
658 Value *llvm::UpgradeBitCastExpr(unsigned Opc, Constant *C, Type *DestTy) {
659   if (Opc != Instruction::BitCast)
660     return nullptr;
661
662   Type *SrcTy = C->getType();
663   if (SrcTy->isPtrOrPtrVectorTy() && DestTy->isPtrOrPtrVectorTy() &&
664       SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace()) {
665     LLVMContext &Context = C->getContext();
666
667     // We have no information about target data layout, so we assume that
668     // the maximum pointer size is 64bit.
669     Type *MidTy = Type::getInt64Ty(Context);
670
671     return ConstantExpr::getIntToPtr(ConstantExpr::getPtrToInt(C, MidTy),
672                                      DestTy);
673   }
674
675   return nullptr;
676 }
677
678 /// Check the debug info version number, if it is out-dated, drop the debug
679 /// info. Return true if module is modified.
680 bool llvm::UpgradeDebugInfo(Module &M) {
681   unsigned Version = getDebugMetadataVersionFromModule(M);
682   if (Version == DEBUG_METADATA_VERSION)
683     return false;
684
685   bool RetCode = StripDebugInfo(M);
686   if (RetCode) {
687     DiagnosticInfoDebugMetadataVersion DiagVersion(M, Version);
688     M.getContext().diagnose(DiagVersion);
689   }
690   return RetCode;
691 }
692
693 void llvm::UpgradeMDStringConstant(std::string &String) {
694   const std::string OldPrefix = "llvm.vectorizer.";
695   if (String == "llvm.vectorizer.unroll") {
696     String = "llvm.loop.interleave.count";
697   } else if (String.find(OldPrefix) == 0) {
698     String.replace(0, OldPrefix.size(), "llvm.loop.vectorize.");
699   }
700 }