IR: Split Metadata from Value
[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 MetadataAsValue *getExpression(Value *VarOperand, Function *F) {
264   // Old-style DIVariables have an optional expression as the 8th element.
265   DIExpression Expr(getNodeField(
266       cast<MDNode>(cast<MetadataAsValue>(VarOperand)->getMetadata()), 8));
267   if (!Expr) {
268     DIBuilder DIB(*F->getParent(), /*AllowUnresolved*/ false);
269     Expr = DIB.createExpression();
270   }
271   return MetadataAsValue::get(F->getContext(), Expr);
272 }
273
274 // UpgradeIntrinsicCall - Upgrade a call to an old intrinsic to be a call the
275 // upgraded intrinsic. All argument and return casting must be provided in
276 // order to seamlessly integrate with existing context.
277 void llvm::UpgradeIntrinsicCall(CallInst *CI, Function *NewFn) {
278   Function *F = CI->getCalledFunction();
279   LLVMContext &C = CI->getContext();
280   IRBuilder<> Builder(C);
281   Builder.SetInsertPoint(CI->getParent(), CI);
282
283   assert(F && "Intrinsic call is not direct?");
284
285   if (!NewFn) {
286     // Get the Function's name.
287     StringRef Name = F->getName();
288
289     Value *Rep;
290     // Upgrade packed integer vector compares intrinsics to compare instructions
291     if (Name.startswith("llvm.x86.sse2.pcmpeq.") ||
292         Name.startswith("llvm.x86.avx2.pcmpeq.")) {
293       Rep = Builder.CreateICmpEQ(CI->getArgOperand(0), CI->getArgOperand(1),
294                                  "pcmpeq");
295       // need to sign extend since icmp returns vector of i1
296       Rep = Builder.CreateSExt(Rep, CI->getType(), "");
297     } else if (Name.startswith("llvm.x86.sse2.pcmpgt.") ||
298                Name.startswith("llvm.x86.avx2.pcmpgt.")) {
299       Rep = Builder.CreateICmpSGT(CI->getArgOperand(0), CI->getArgOperand(1),
300                                   "pcmpgt");
301       // need to sign extend since icmp returns vector of i1
302       Rep = Builder.CreateSExt(Rep, CI->getType(), "");
303     } else if (Name == "llvm.x86.avx.movnt.dq.256" ||
304                Name == "llvm.x86.avx.movnt.ps.256" ||
305                Name == "llvm.x86.avx.movnt.pd.256") {
306       IRBuilder<> Builder(C);
307       Builder.SetInsertPoint(CI->getParent(), CI);
308
309       Module *M = F->getParent();
310       SmallVector<Metadata *, 1> Elts;
311       Elts.push_back(
312           ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(C), 1)));
313       MDNode *Node = MDNode::get(C, Elts);
314
315       Value *Arg0 = CI->getArgOperand(0);
316       Value *Arg1 = CI->getArgOperand(1);
317
318       // Convert the type of the pointer to a pointer to the stored type.
319       Value *BC = Builder.CreateBitCast(Arg0,
320                                         PointerType::getUnqual(Arg1->getType()),
321                                         "cast");
322       StoreInst *SI = Builder.CreateStore(Arg1, BC);
323       SI->setMetadata(M->getMDKindID("nontemporal"), Node);
324       SI->setAlignment(16);
325
326       // Remove intrinsic.
327       CI->eraseFromParent();
328       return;
329     } else if (Name.startswith("llvm.x86.xop.vpcom")) {
330       Intrinsic::ID intID;
331       if (Name.endswith("ub"))
332         intID = Intrinsic::x86_xop_vpcomub;
333       else if (Name.endswith("uw"))
334         intID = Intrinsic::x86_xop_vpcomuw;
335       else if (Name.endswith("ud"))
336         intID = Intrinsic::x86_xop_vpcomud;
337       else if (Name.endswith("uq"))
338         intID = Intrinsic::x86_xop_vpcomuq;
339       else if (Name.endswith("b"))
340         intID = Intrinsic::x86_xop_vpcomb;
341       else if (Name.endswith("w"))
342         intID = Intrinsic::x86_xop_vpcomw;
343       else if (Name.endswith("d"))
344         intID = Intrinsic::x86_xop_vpcomd;
345       else if (Name.endswith("q"))
346         intID = Intrinsic::x86_xop_vpcomq;
347       else
348         llvm_unreachable("Unknown suffix");
349
350       Name = Name.substr(18); // strip off "llvm.x86.xop.vpcom"
351       unsigned Imm;
352       if (Name.startswith("lt"))
353         Imm = 0;
354       else if (Name.startswith("le"))
355         Imm = 1;
356       else if (Name.startswith("gt"))
357         Imm = 2;
358       else if (Name.startswith("ge"))
359         Imm = 3;
360       else if (Name.startswith("eq"))
361         Imm = 4;
362       else if (Name.startswith("ne"))
363         Imm = 5;
364       else if (Name.startswith("true"))
365         Imm = 6;
366       else if (Name.startswith("false"))
367         Imm = 7;
368       else
369         llvm_unreachable("Unknown condition");
370
371       Function *VPCOM = Intrinsic::getDeclaration(F->getParent(), intID);
372       Rep = Builder.CreateCall3(VPCOM, CI->getArgOperand(0),
373                                 CI->getArgOperand(1), Builder.getInt8(Imm));
374     } else if (Name == "llvm.x86.sse42.crc32.64.8") {
375       Function *CRC32 = Intrinsic::getDeclaration(F->getParent(),
376                                                Intrinsic::x86_sse42_crc32_32_8);
377       Value *Trunc0 = Builder.CreateTrunc(CI->getArgOperand(0), Type::getInt32Ty(C));
378       Rep = Builder.CreateCall2(CRC32, Trunc0, CI->getArgOperand(1));
379       Rep = Builder.CreateZExt(Rep, CI->getType(), "");
380     } else if (Name.startswith("llvm.x86.avx.vbroadcast")) {
381       // Replace broadcasts with a series of insertelements.
382       Type *VecTy = CI->getType();
383       Type *EltTy = VecTy->getVectorElementType();
384       unsigned EltNum = VecTy->getVectorNumElements();
385       Value *Cast = Builder.CreateBitCast(CI->getArgOperand(0),
386                                           EltTy->getPointerTo());
387       Value *Load = Builder.CreateLoad(Cast);
388       Type *I32Ty = Type::getInt32Ty(C);
389       Rep = UndefValue::get(VecTy);
390       for (unsigned I = 0; I < EltNum; ++I)
391         Rep = Builder.CreateInsertElement(Rep, Load,
392                                           ConstantInt::get(I32Ty, I));
393     } else {
394       bool PD128 = false, PD256 = false, PS128 = false, PS256 = false;
395       if (Name == "llvm.x86.avx.vpermil.pd.256")
396         PD256 = true;
397       else if (Name == "llvm.x86.avx.vpermil.pd")
398         PD128 = true;
399       else if (Name == "llvm.x86.avx.vpermil.ps.256")
400         PS256 = true;
401       else if (Name == "llvm.x86.avx.vpermil.ps")
402         PS128 = true;
403
404       if (PD256 || PD128 || PS256 || PS128) {
405         Value *Op0 = CI->getArgOperand(0);
406         unsigned Imm = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
407         SmallVector<Constant*, 8> Idxs;
408
409         if (PD128)
410           for (unsigned i = 0; i != 2; ++i)
411             Idxs.push_back(Builder.getInt32((Imm >> i) & 0x1));
412         else if (PD256)
413           for (unsigned l = 0; l != 4; l+=2)
414             for (unsigned i = 0; i != 2; ++i)
415               Idxs.push_back(Builder.getInt32(((Imm >> (l+i)) & 0x1) + l));
416         else if (PS128)
417           for (unsigned i = 0; i != 4; ++i)
418             Idxs.push_back(Builder.getInt32((Imm >> (2 * i)) & 0x3));
419         else if (PS256)
420           for (unsigned l = 0; l != 8; l+=4)
421             for (unsigned i = 0; i != 4; ++i)
422               Idxs.push_back(Builder.getInt32(((Imm >> (2 * i)) & 0x3) + l));
423         else
424           llvm_unreachable("Unexpected function");
425
426         Rep = Builder.CreateShuffleVector(Op0, Op0, ConstantVector::get(Idxs));
427       } else {
428         llvm_unreachable("Unknown function for CallInst upgrade.");
429       }
430     }
431
432     CI->replaceAllUsesWith(Rep);
433     CI->eraseFromParent();
434     return;
435   }
436
437   std::string Name = CI->getName().str();
438   if (!Name.empty())
439     CI->setName(Name + ".old");
440
441   switch (NewFn->getIntrinsicID()) {
442   default:
443     llvm_unreachable("Unknown function for CallInst upgrade.");
444
445   // Upgrade debug intrinsics to use an additional DIExpression argument.
446   case Intrinsic::dbg_declare: {
447     auto NewCI =
448         Builder.CreateCall3(NewFn, CI->getArgOperand(0), CI->getArgOperand(1),
449                             getExpression(CI->getArgOperand(1), F), Name);
450     NewCI->setDebugLoc(CI->getDebugLoc());
451     CI->replaceAllUsesWith(NewCI);
452     CI->eraseFromParent();
453     return;
454   }
455   case Intrinsic::dbg_value: {
456     auto NewCI = Builder.CreateCall4(
457         NewFn, CI->getArgOperand(0), CI->getArgOperand(1), CI->getArgOperand(2),
458         getExpression(CI->getArgOperand(2), F), Name);
459     NewCI->setDebugLoc(CI->getDebugLoc());
460     CI->replaceAllUsesWith(NewCI);
461     CI->eraseFromParent();
462     return;
463   }
464   case Intrinsic::ctlz:
465   case Intrinsic::cttz:
466     assert(CI->getNumArgOperands() == 1 &&
467            "Mismatch between function args and call args");
468     CI->replaceAllUsesWith(Builder.CreateCall2(NewFn, CI->getArgOperand(0),
469                                                Builder.getFalse(), Name));
470     CI->eraseFromParent();
471     return;
472
473   case Intrinsic::objectsize:
474     CI->replaceAllUsesWith(Builder.CreateCall2(NewFn,
475                                                CI->getArgOperand(0),
476                                                CI->getArgOperand(1),
477                                                Name));
478     CI->eraseFromParent();
479     return;
480
481   case Intrinsic::ctpop: {
482     CI->replaceAllUsesWith(Builder.CreateCall(NewFn, CI->getArgOperand(0)));
483     CI->eraseFromParent();
484     return;
485   }
486
487   case Intrinsic::x86_xop_vfrcz_ss:
488   case Intrinsic::x86_xop_vfrcz_sd:
489     CI->replaceAllUsesWith(Builder.CreateCall(NewFn, CI->getArgOperand(1),
490                                               Name));
491     CI->eraseFromParent();
492     return;
493
494   case Intrinsic::x86_sse41_ptestc:
495   case Intrinsic::x86_sse41_ptestz:
496   case Intrinsic::x86_sse41_ptestnzc: {
497     // The arguments for these intrinsics used to be v4f32, and changed
498     // to v2i64. This is purely a nop, since those are bitwise intrinsics.
499     // So, the only thing required is a bitcast for both arguments.
500     // First, check the arguments have the old type.
501     Value *Arg0 = CI->getArgOperand(0);
502     if (Arg0->getType() != VectorType::get(Type::getFloatTy(C), 4))
503       return;
504
505     // Old intrinsic, add bitcasts
506     Value *Arg1 = CI->getArgOperand(1);
507
508     Value *BC0 =
509       Builder.CreateBitCast(Arg0,
510                             VectorType::get(Type::getInt64Ty(C), 2),
511                             "cast");
512     Value *BC1 =
513       Builder.CreateBitCast(Arg1,
514                             VectorType::get(Type::getInt64Ty(C), 2),
515                             "cast");
516
517     CallInst* NewCall = Builder.CreateCall2(NewFn, BC0, BC1, Name);
518     CI->replaceAllUsesWith(NewCall);
519     CI->eraseFromParent();
520     return;
521   }
522
523   case Intrinsic::x86_sse41_pblendw:
524   case Intrinsic::x86_sse41_blendpd:
525   case Intrinsic::x86_sse41_blendps:
526   case Intrinsic::x86_sse41_insertps:
527   case Intrinsic::x86_sse41_dppd:
528   case Intrinsic::x86_sse41_dpps:
529   case Intrinsic::x86_sse41_mpsadbw:
530   case Intrinsic::x86_avx_blend_pd_256:
531   case Intrinsic::x86_avx_blend_ps_256:
532   case Intrinsic::x86_avx_dp_ps_256:
533   case Intrinsic::x86_avx2_pblendw:
534   case Intrinsic::x86_avx2_pblendd_128:
535   case Intrinsic::x86_avx2_pblendd_256:
536   case Intrinsic::x86_avx2_mpsadbw: {
537     // Need to truncate the last argument from i32 to i8 -- this argument models
538     // an inherently 8-bit immediate operand to these x86 instructions.
539     SmallVector<Value *, 4> Args(CI->arg_operands().begin(),
540                                  CI->arg_operands().end());
541
542     // Replace the last argument with a trunc.
543     Args.back() = Builder.CreateTrunc(Args.back(), Type::getInt8Ty(C), "trunc");
544
545     CallInst *NewCall = Builder.CreateCall(NewFn, Args);
546     CI->replaceAllUsesWith(NewCall);
547     CI->eraseFromParent();
548     return;
549   }
550   }
551 }
552
553 // This tests each Function to determine if it needs upgrading. When we find
554 // one we are interested in, we then upgrade all calls to reflect the new
555 // function.
556 void llvm::UpgradeCallsToIntrinsic(Function* F) {
557   assert(F && "Illegal attempt to upgrade a non-existent intrinsic.");
558
559   // Upgrade the function and check if it is a totaly new function.
560   Function *NewFn;
561   if (UpgradeIntrinsicFunction(F, NewFn)) {
562     if (NewFn != F) {
563       // Replace all uses to the old function with the new one if necessary.
564       for (Value::user_iterator UI = F->user_begin(), UE = F->user_end();
565            UI != UE; ) {
566         if (CallInst *CI = dyn_cast<CallInst>(*UI++))
567           UpgradeIntrinsicCall(CI, NewFn);
568       }
569       // Remove old function, no longer used, from the module.
570       F->eraseFromParent();
571     }
572   }
573 }
574
575 void llvm::UpgradeInstWithTBAATag(Instruction *I) {
576   MDNode *MD = I->getMetadata(LLVMContext::MD_tbaa);
577   assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
578   // Check if the tag uses struct-path aware TBAA format.
579   if (isa<MDNode>(MD->getOperand(0)) && MD->getNumOperands() >= 3)
580     return;
581
582   if (MD->getNumOperands() == 3) {
583     Metadata *Elts[] = {MD->getOperand(0), MD->getOperand(1)};
584     MDNode *ScalarType = MDNode::get(I->getContext(), Elts);
585     // Create a MDNode <ScalarType, ScalarType, offset 0, const>
586     Metadata *Elts2[] = {ScalarType, ScalarType,
587                          ConstantAsMetadata::get(Constant::getNullValue(
588                              Type::getInt64Ty(I->getContext()))),
589                          MD->getOperand(2)};
590     I->setMetadata(LLVMContext::MD_tbaa, MDNode::get(I->getContext(), Elts2));
591   } else {
592     // Create a MDNode <MD, MD, offset 0>
593     Metadata *Elts[] = {MD, MD, ConstantAsMetadata::get(Constant::getNullValue(
594                                     Type::getInt64Ty(I->getContext())))};
595     I->setMetadata(LLVMContext::MD_tbaa, MDNode::get(I->getContext(), Elts));
596   }
597 }
598
599 Instruction *llvm::UpgradeBitCastInst(unsigned Opc, Value *V, Type *DestTy,
600                                       Instruction *&Temp) {
601   if (Opc != Instruction::BitCast)
602     return nullptr;
603
604   Temp = nullptr;
605   Type *SrcTy = V->getType();
606   if (SrcTy->isPtrOrPtrVectorTy() && DestTy->isPtrOrPtrVectorTy() &&
607       SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace()) {
608     LLVMContext &Context = V->getContext();
609
610     // We have no information about target data layout, so we assume that
611     // the maximum pointer size is 64bit.
612     Type *MidTy = Type::getInt64Ty(Context);
613     Temp = CastInst::Create(Instruction::PtrToInt, V, MidTy);
614
615     return CastInst::Create(Instruction::IntToPtr, Temp, DestTy);
616   }
617
618   return nullptr;
619 }
620
621 Value *llvm::UpgradeBitCastExpr(unsigned Opc, Constant *C, Type *DestTy) {
622   if (Opc != Instruction::BitCast)
623     return nullptr;
624
625   Type *SrcTy = C->getType();
626   if (SrcTy->isPtrOrPtrVectorTy() && DestTy->isPtrOrPtrVectorTy() &&
627       SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace()) {
628     LLVMContext &Context = C->getContext();
629
630     // We have no information about target data layout, so we assume that
631     // the maximum pointer size is 64bit.
632     Type *MidTy = Type::getInt64Ty(Context);
633
634     return ConstantExpr::getIntToPtr(ConstantExpr::getPtrToInt(C, MidTy),
635                                      DestTy);
636   }
637
638   return nullptr;
639 }
640
641 /// Check the debug info version number, if it is out-dated, drop the debug
642 /// info. Return true if module is modified.
643 bool llvm::UpgradeDebugInfo(Module &M) {
644   unsigned Version = getDebugMetadataVersionFromModule(M);
645   if (Version == DEBUG_METADATA_VERSION)
646     return false;
647
648   bool RetCode = StripDebugInfo(M);
649   if (RetCode) {
650     DiagnosticInfoDebugMetadataVersion DiagVersion(M, Version);
651     M.getContext().diagnose(DiagVersion);
652   }
653   return RetCode;
654 }
655
656 void llvm::UpgradeMDStringConstant(std::string &String) {
657   const std::string OldPrefix = "llvm.vectorizer.";
658   if (String == "llvm.vectorizer.unroll") {
659     String = "llvm.loop.interleave.count";
660   } else if (String.find(OldPrefix) == 0) {
661     String.replace(0, OldPrefix.size(), "llvm.loop.vectorize.");
662   }
663 }