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