InstCombineCalls.cpp revision 1df9859c40492511b8aa4321eb76496005d3b75b
15c02ac1a9c1b504631c0a3d2b6e737b5d738bae1Bo Liu//===- InstCombineCalls.cpp -----------------------------------------------===//
25821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//
35821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//                     The LLVM Compiler Infrastructure
45821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//
55821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// This file is distributed under the University of Illinois Open Source
65821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// License. See LICENSE.TXT for details.
75821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//
85821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//===----------------------------------------------------------------------===//
91320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci//
101320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci// This file implements the visitCall and visitInvoke functions.
115821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//
125821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//===----------------------------------------------------------------------===//
135821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
145821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "InstCombine.h"
155821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "llvm/IntrinsicInst.h"
165821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "llvm/Support/CallSite.h"
175821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "llvm/Target/TargetData.h"
185821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "llvm/Analysis/MemoryBuiltins.h"
195821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)using namespace llvm;
205821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
2103b57e008b61dfcb1fbad3aea950ae0e001748b0Torne (Richard Coles)/// getPromotedType - Return the specified type promoted as it would be to pass
2203b57e008b61dfcb1fbad3aea950ae0e001748b0Torne (Richard Coles)/// though a va_arg area.
2303b57e008b61dfcb1fbad3aea950ae0e001748b0Torne (Richard Coles)static const Type *getPromotedType(const Type *Ty) {
2403b57e008b61dfcb1fbad3aea950ae0e001748b0Torne (Richard Coles)  if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
2503b57e008b61dfcb1fbad3aea950ae0e001748b0Torne (Richard Coles)    if (ITy->getBitWidth() < 32)
2603b57e008b61dfcb1fbad3aea950ae0e001748b0Torne (Richard Coles)      return Type::getInt32Ty(Ty->getContext());
275c02ac1a9c1b504631c0a3d2b6e737b5d738bae1Bo Liu  }
285c02ac1a9c1b504631c0a3d2b6e737b5d738bae1Bo Liu  return Ty;
295821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)}
302a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
315821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)/// EnforceKnownAlignment - If the specified pointer points to an object that
325821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)/// we control, modify the object's alignment to PrefAlign. This isn't
335821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)/// often possible though. If alignment is important, a more reliable approach
342a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)/// is to simply align all global variables and allocation instructions to
352a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)/// their preferred alignment from the beginning.
362a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)///
372a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)static unsigned EnforceKnownAlignment(Value *V,
382a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                                      unsigned Align, unsigned PrefAlign) {
395821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
402a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  User *U = dyn_cast<User>(V);
412a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (!U) return Align;
425821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
435821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  switch (Operator::getOpcode(U)) {
442a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  default: break;
452a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  case Instruction::BitCast:
462a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
475821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  case Instruction::GetElementPtr: {
485821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    // If all indexes are zero, it is just the alignment of the base pointer.
495821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    bool AllZeroOperands = true;
505821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
515821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      if (!isa<Constant>(*i) ||
525821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)          !cast<Constant>(*i)->isNullValue()) {
535821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)        AllZeroOperands = false;
545821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)        break;
555821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      }
565821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
575821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    if (AllZeroOperands) {
582a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      // Treat this like a bitcast.
595821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
605821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    }
615821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    break;
625821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  }
635821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  }
645821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
655821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
665821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    // If there is a large requested alignment and we can, bump up the alignment
675821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    // of the global.
685821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    if (!GV->isDeclaration()) {
695821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      if (GV->getAlignment() >= PrefAlign)
705821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)        Align = GV->getAlignment();
712a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      else {
725821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)        GV->setAlignment(PrefAlign);
735821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)        Align = PrefAlign;
745821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      }
755821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    }
765821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
775821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    // If there is a requested alignment and if this is an alloca, round up.
785821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    if (AI->getAlignment() >= PrefAlign)
795821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      Align = AI->getAlignment();
805821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    else {
812a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      AI->setAlignment(PrefAlign);
825821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      Align = PrefAlign;
835821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    }
845821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  }
855821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
865821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  return Align;
875821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)}
885821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
895821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
905821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)/// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
915821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)/// and it is more than the alignment of the ultimate object, see if we can
925821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)/// increase the alignment of the ultimate object, making this check succeed.
935821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
945821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                                                  unsigned PrefAlign) {
955821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
965821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                      sizeof(PrefAlign) * CHAR_BIT;
975821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  APInt Mask = APInt::getAllOnesValue(BitWidth);
985821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
995821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
1005821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  unsigned TrailZ = KnownZero.countTrailingOnes();
1012a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
1025821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
1035821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  if (PrefAlign > Align)
1042a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    Align = EnforceKnownAlignment(V, Align, PrefAlign);
1056d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)
10603b57e008b61dfcb1fbad3aea950ae0e001748b0Torne (Richard Coles)    // We don't need to make any adjustment.
107a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)  return Align;
1082a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
1096d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)
1106d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
1115821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
1125821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
1135821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  unsigned MinAlign = std::min(DstAlign, SrcAlign);
1145821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  unsigned CopyAlign = MI->getAlignment();
1156d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)
1165821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  if (CopyAlign < MinAlign) {
1175821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
1185821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                                             MinAlign, false));
1195821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    return MI;
1202a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
1215821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
1225821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
1235821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // load/store.
1245821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
1255821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  if (MemOpLength == 0) return 0;
1265821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
1276d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)  // Source and destination pointer types are always "i8*" for intrinsic.  See
1286d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)  // if the size is something we can handle with a single primitive load/store.
1295821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // A single load+store correctly handles overlapping memory in the memmove
1305821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // case.
1315821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  unsigned Size = MemOpLength->getZExtValue();
1325821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  if (Size == 0) return MI;  // Delete this mem transfer.
1335821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
1345821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  if (Size > 8 || (Size&(Size-1)))
1355821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    return 0;  // If not 1/2/4/8 bytes, exit.
1365821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
1375821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // Use an integer load+store unless we can find something better.
1385821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  Type *NewPtrTy =
1395821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)            PointerType::getUnqual(IntegerType::get(MI->getContext(), Size<<3));
1406d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)
1415821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // Memcpy forces the use of i8* for the source and destination.  That means
1426d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)  // that if you're using memcpy to move one double around, you'll get a cast
1435821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // from double* to i8*.  We'd much rather use a double load+store rather than
1446d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)  // an i64 load+store, here because this improves the odds that the source or
1455821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // dest address will be promotable.  See if we can find a better type than the
1465821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // integer datatype.
1475821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  Value *StrippedDest = MI->getOperand(1)->stripPointerCasts();
1485821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  if (StrippedDest != MI->getOperand(1)) {
1495821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    const Type *SrcETy = cast<PointerType>(StrippedDest->getType())
1505821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                                    ->getElementType();
1515821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
1525821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
1535821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      // down through these levels if so.
1545821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      while (!SrcETy->isSingleValueType()) {
1555821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)        if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
1565821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)          if (STy->getNumElements() == 1)
1575821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)            SrcETy = STy->getElementType(0);
1585821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)          else
1595821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)            break;
1605821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)        } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
1615821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)          if (ATy->getNumElements() == 1)
1625821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)            SrcETy = ATy->getElementType();
1635821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)          else
1645821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)            break;
1655821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)        } else
1665821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)          break;
1675821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      }
1685821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
1695821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      if (SrcETy->isSingleValueType())
1705821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)        NewPtrTy = PointerType::getUnqual(SrcETy);
1715821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    }
1725821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  }
1735821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
1745821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
1755821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // If the memcpy/memmove provides better alignment info than we can
1765821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // infer, use it.
1775821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  SrcAlign = std::max(SrcAlign, CopyAlign);
1785821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  DstAlign = std::max(DstAlign, CopyAlign);
1795821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
1802a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
1815821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
1825821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
1835821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  InsertNewInstBefore(L, *MI);
1845821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
1855821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
1865821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // Set the size of the copy to 0, it will be deleted on the next iteration.
1875821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
1885821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  return MI;
1895821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)}
1905821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
1915821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
1925821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
1935821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  if (MI->getAlignment() < Alignment) {
1945821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
1955821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                                             Alignment, false));
1965821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    return MI;
1975821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  }
1985821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
1995821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // Extract the length and alignment and fill if they are constant.
2005821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
2014e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)  ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
2024e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)  if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
2034e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)    return 0;
2045821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  uint64_t Len = LenC->getZExtValue();
2052a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  Alignment = MI->getAlignment();
20603b57e008b61dfcb1fbad3aea950ae0e001748b0Torne (Richard Coles)
2076d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)  // If the length is zero, this is a no-op
208a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)  if (Len == 0) return MI; // memset(d,c,0,a) -> noop
2095821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
2102a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // memset(s,c,n) -> store s, c (for n=1,2,4,8)
2116d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)  if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
2126d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)    const Type *ITy = IntegerType::get(MI->getContext(), Len*8);  // n=1 -> i8.
2135821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
2145821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    Value *Dest = MI->getDest();
2152a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
2166d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)
2176d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)    // Alignment 0 is identity for alignment 1 for memset, but not store.
2185821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    if (Alignment == 0) Alignment = 1;
2195821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
2205821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    // Extract the fill value and store.
2215821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
2225821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
2236d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)                                      Dest, false, Alignment), *MI);
2245821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
2255821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    // Set the size of the copy to 0, it will be deleted on the next iteration.
2265821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    MI->setLength(Constant::getNullValue(LenC->getType()));
2275821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    return MI;
2282a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
2292a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
2302a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  return 0;
2312a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
2322a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
2332a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)/// visitCallInst - CallInst simplification.  This mostly only handles folding
2342a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)/// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
2352a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)/// the heavy lifting.
2362a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)///
2372a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)Instruction *InstCombiner::visitCallInst(CallInst &CI) {
2382a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (isFreeCall(&CI))
2392a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    return visitFree(CI);
2402a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
2412a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // If the caller function is nounwind, mark the call as nounwind, even if the
2422a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  // callee isn't.
2432a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (CI.getParent()->getParent()->doesNotThrow() &&
2442a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      !CI.doesNotThrow()) {
2452a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    CI.setDoesNotThrow();
2462a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    return &CI;
2472a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
2482a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
2492a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
2502a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (!II) return visitCallSite(&CI);
2514e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)
2524e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)  // Intrinsics cannot occur in an invoke, so handle them here instead of in
2534e180b6a0b4720a9b8e9e959a882386f690f08ffTorne (Richard Coles)  // visitCallSite.
2542a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
2552a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    bool Changed = false;
2562a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
2572a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    // memmove/cpy/set of zero bytes is a noop.
2582a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
2592a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
2602a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
2612a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
2622a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        if (CI->getZExtValue() == 1) {
2632a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)          // Replace the instruction with just byte operations.  We would
2642a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)          // transform other cases to loads/stores, but we don't know if
2652a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)          // alignment is sufficient.
2662a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        }
2672a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    }
2682a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
2692a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    // If we have a memmove and the source operation is a constant global,
2702a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    // then the source and dest pointers can't alias, so we can change this
2712a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    // into a call to memcpy.
2722a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
2732a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
2745821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)        if (GVSrc->isConstant()) {
2755821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)          Module *M = CI.getParent()->getParent()->getParent();
2762a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)          Intrinsic::ID MemCpyID = Intrinsic::memcpy;
277a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)          const Type *Tys[1];
2785821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)          Tys[0] = CI.getOperand(3)->getType();
2795821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)          CI.setOperand(0,
2805821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                        Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
2815821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)          Changed = true;
2822a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        }
2832a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    }
2846d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)
2855821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
2865821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      // memmove(x,x,size) -> noop.
2875821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      if (MTI->getSource() == MTI->getDest())
2885821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)        return EraseInstFromFunction(CI);
2895821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    }
2905821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
2915821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    // If we can determine a pointer alignment that is bigger than currently
2922a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    // set, update the alignment.
2936d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)    if (isa<MemTransferInst>(MI)) {
2945821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      if (Instruction *I = SimplifyMemTransfer(MI))
2955821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)        return I;
2962a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
2972a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      if (Instruction *I = SimplifyMemSet(MSI))
2982a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        return I;
2992a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    }
3002a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
3012a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    if (Changed) return II;
30203b57e008b61dfcb1fbad3aea950ae0e001748b0Torne (Richard Coles)  }
3032a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
3042a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  switch (II->getIntrinsicID()) {
3052a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  default: break;
30603b57e008b61dfcb1fbad3aea950ae0e001748b0Torne (Richard Coles)  case Intrinsic::objectsize: {
3072a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    const Type *ReturnTy = CI.getType();
30803b57e008b61dfcb1fbad3aea950ae0e001748b0Torne (Richard Coles)    Value *Op1 = II->getOperand(1);
3092a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    bool Min = (cast<ConstantInt>(II->getOperand(2))->getZExtValue() == 1);
31003b57e008b61dfcb1fbad3aea950ae0e001748b0Torne (Richard Coles)
3112a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    // We need target data for just about everything so depend on it.
31203b57e008b61dfcb1fbad3aea950ae0e001748b0Torne (Richard Coles)    if (!TD) break;
3132a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
3142a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    // Get to the real allocated thing and offset as fast as possible.
31503b57e008b61dfcb1fbad3aea950ae0e001748b0Torne (Richard Coles)    Op1 = Op1->stripPointerCasts();
3162a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
31703b57e008b61dfcb1fbad3aea950ae0e001748b0Torne (Richard Coles)    // If we've stripped down to a single global variable that we
3182a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    // can know the size of then just return that.
31903b57e008b61dfcb1fbad3aea950ae0e001748b0Torne (Richard Coles)    if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op1)) {
3202a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      if (GV->hasDefinitiveInitializer()) {
32103b57e008b61dfcb1fbad3aea950ae0e001748b0Torne (Richard Coles)        Constant *C = GV->getInitializer();
3222a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        size_t globalSize = TD->getTypeAllocSize(C->getType());
3232a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)        return ReplaceInstUsesWith(CI, ConstantInt::get(ReturnTy, globalSize));
32490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      } else {
32590dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)        Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
32690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)        return ReplaceInstUsesWith(CI, RetVal);
32703b57e008b61dfcb1fbad3aea950ae0e001748b0Torne (Richard Coles)      }
32890dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op1)) {
32990dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
33003b57e008b61dfcb1fbad3aea950ae0e001748b0Torne (Richard Coles)      // Only handle constant GEPs here.
33103b57e008b61dfcb1fbad3aea950ae0e001748b0Torne (Richard Coles)      if (CE->getOpcode() != Instruction::GetElementPtr) break;
33290dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      GEPOperator *GEP = cast<GEPOperator>(CE);
33390dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
33490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      // Make sure we're not a constant offset from an external
33590dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      // global.
33690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      Value *Operand = GEP->getPointerOperand();
33790dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      Operand = Operand->stripPointerCasts();
33890dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Operand))
33990dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)        if (!GV->hasDefinitiveInitializer()) break;
34003b57e008b61dfcb1fbad3aea950ae0e001748b0Torne (Richard Coles)
34190dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      // Get what we're pointing to and its size.
34290dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      const PointerType *BaseType =
34390dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)        cast<PointerType>(Operand->getType());
34490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      size_t Size = TD->getTypeAllocSize(BaseType->getElementType());
34590dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
34690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      // Get the current byte offset into the thing. Use the original
34790dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      // operand in case we're looking through a bitcast.
34890dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      SmallVector<Value*, 8> Ops(CE->op_begin()+1, CE->op_end());
34990dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      const PointerType *OffsetType =
35090dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)        cast<PointerType>(GEP->getPointerOperand()->getType());
3516d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)      size_t Offset = TD->getIndexedOffset(OffsetType, &Ops[0], Ops.size());
352a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)
35390dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      assert(Size >= Offset);
3546d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)
3556d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)      Constant *RetVal = ConstantInt::get(ReturnTy, Size-Offset);
35690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      return ReplaceInstUsesWith(CI, RetVal);
35790dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
3586d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)    }
35990dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  }
36090dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  case Intrinsic::bswap:
3615c02ac1a9c1b504631c0a3d2b6e737b5d738bae1Bo Liu    // bswap(bswap(x)) -> x
362    if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
363      if (Operand->getIntrinsicID() == Intrinsic::bswap)
364        return ReplaceInstUsesWith(CI, Operand->getOperand(1));
365
366    // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
367    if (TruncInst *TI = dyn_cast<TruncInst>(II->getOperand(1))) {
368      if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(TI->getOperand(0)))
369        if (Operand->getIntrinsicID() == Intrinsic::bswap) {
370          unsigned C = Operand->getType()->getPrimitiveSizeInBits() -
371                       TI->getType()->getPrimitiveSizeInBits();
372          Value *CV = ConstantInt::get(Operand->getType(), C);
373          Value *V = Builder->CreateLShr(Operand->getOperand(1), CV);
374          return new TruncInst(V, TI->getType());
375        }
376    }
377
378    break;
379  case Intrinsic::powi:
380    if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getOperand(2))) {
381      // powi(x, 0) -> 1.0
382      if (Power->isZero())
383        return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
384      // powi(x, 1) -> x
385      if (Power->isOne())
386        return ReplaceInstUsesWith(CI, II->getOperand(1));
387      // powi(x, -1) -> 1/x
388      if (Power->isAllOnesValue())
389        return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
390                                          II->getOperand(1));
391    }
392    break;
393  case Intrinsic::cttz: {
394    // If all bits below the first known one are known zero,
395    // this value is constant.
396    const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
397    uint32_t BitWidth = IT->getBitWidth();
398    APInt KnownZero(BitWidth, 0);
399    APInt KnownOne(BitWidth, 0);
400    ComputeMaskedBits(II->getOperand(1), APInt::getAllOnesValue(BitWidth),
401                      KnownZero, KnownOne);
402    unsigned TrailingZeros = KnownOne.countTrailingZeros();
403    APInt Mask(APInt::getLowBitsSet(BitWidth, TrailingZeros));
404    if ((Mask & KnownZero) == Mask)
405      return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
406                                 APInt(BitWidth, TrailingZeros)));
407
408    }
409    break;
410  case Intrinsic::ctlz: {
411    // If all bits above the first known one are known zero,
412    // this value is constant.
413    const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
414    uint32_t BitWidth = IT->getBitWidth();
415    APInt KnownZero(BitWidth, 0);
416    APInt KnownOne(BitWidth, 0);
417    ComputeMaskedBits(II->getOperand(1), APInt::getAllOnesValue(BitWidth),
418                      KnownZero, KnownOne);
419    unsigned LeadingZeros = KnownOne.countLeadingZeros();
420    APInt Mask(APInt::getHighBitsSet(BitWidth, LeadingZeros));
421    if ((Mask & KnownZero) == Mask)
422      return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
423                                 APInt(BitWidth, LeadingZeros)));
424
425    }
426    break;
427  case Intrinsic::uadd_with_overflow: {
428    Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
429    const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
430    uint32_t BitWidth = IT->getBitWidth();
431    APInt Mask = APInt::getSignBit(BitWidth);
432    APInt LHSKnownZero(BitWidth, 0);
433    APInt LHSKnownOne(BitWidth, 0);
434    ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
435    bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
436    bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
437
438    if (LHSKnownNegative || LHSKnownPositive) {
439      APInt RHSKnownZero(BitWidth, 0);
440      APInt RHSKnownOne(BitWidth, 0);
441      ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
442      bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
443      bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
444      if (LHSKnownNegative && RHSKnownNegative) {
445        // The sign bit is set in both cases: this MUST overflow.
446        // Create a simple add instruction, and insert it into the struct.
447        Instruction *Add = BinaryOperator::CreateAdd(LHS, RHS, "", &CI);
448        Worklist.Add(Add);
449        Constant *V[] = {
450          UndefValue::get(LHS->getType()),ConstantInt::getTrue(II->getContext())
451        };
452        Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
453        return InsertValueInst::Create(Struct, Add, 0);
454      }
455
456      if (LHSKnownPositive && RHSKnownPositive) {
457        // The sign bit is clear in both cases: this CANNOT overflow.
458        // Create a simple add instruction, and insert it into the struct.
459        Instruction *Add = BinaryOperator::CreateNUWAdd(LHS, RHS, "", &CI);
460        Worklist.Add(Add);
461        Constant *V[] = {
462          UndefValue::get(LHS->getType()),
463          ConstantInt::getFalse(II->getContext())
464        };
465        Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
466        return InsertValueInst::Create(Struct, Add, 0);
467      }
468    }
469  }
470  // FALL THROUGH uadd into sadd
471  case Intrinsic::sadd_with_overflow:
472    // Canonicalize constants into the RHS.
473    if (isa<Constant>(II->getOperand(1)) &&
474        !isa<Constant>(II->getOperand(2))) {
475      Value *LHS = II->getOperand(1);
476      II->setOperand(1, II->getOperand(2));
477      II->setOperand(2, LHS);
478      return II;
479    }
480
481    // X + undef -> undef
482    if (isa<UndefValue>(II->getOperand(2)))
483      return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
484
485    if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
486      // X + 0 -> {X, false}
487      if (RHS->isZero()) {
488        Constant *V[] = {
489          UndefValue::get(II->getOperand(0)->getType()),
490          ConstantInt::getFalse(II->getContext())
491        };
492        Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
493        return InsertValueInst::Create(Struct, II->getOperand(1), 0);
494      }
495    }
496    break;
497  case Intrinsic::usub_with_overflow:
498  case Intrinsic::ssub_with_overflow:
499    // undef - X -> undef
500    // X - undef -> undef
501    if (isa<UndefValue>(II->getOperand(1)) ||
502        isa<UndefValue>(II->getOperand(2)))
503      return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
504
505    if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
506      // X - 0 -> {X, false}
507      if (RHS->isZero()) {
508        Constant *V[] = {
509          UndefValue::get(II->getOperand(1)->getType()),
510          ConstantInt::getFalse(II->getContext())
511        };
512        Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
513        return InsertValueInst::Create(Struct, II->getOperand(1), 0);
514      }
515    }
516    break;
517  case Intrinsic::umul_with_overflow:
518  case Intrinsic::smul_with_overflow:
519    // Canonicalize constants into the RHS.
520    if (isa<Constant>(II->getOperand(1)) &&
521        !isa<Constant>(II->getOperand(2))) {
522      Value *LHS = II->getOperand(1);
523      II->setOperand(1, II->getOperand(2));
524      II->setOperand(2, LHS);
525      return II;
526    }
527
528    // X * undef -> undef
529    if (isa<UndefValue>(II->getOperand(2)))
530      return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
531
532    if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getOperand(2))) {
533      // X*0 -> {0, false}
534      if (RHSI->isZero())
535        return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
536
537      // X * 1 -> {X, false}
538      if (RHSI->equalsInt(1)) {
539        Constant *V[] = {
540          UndefValue::get(II->getOperand(1)->getType()),
541          ConstantInt::getFalse(II->getContext())
542        };
543        Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
544        return InsertValueInst::Create(Struct, II->getOperand(1), 0);
545      }
546    }
547    break;
548  case Intrinsic::ppc_altivec_lvx:
549  case Intrinsic::ppc_altivec_lvxl:
550  case Intrinsic::x86_sse_loadu_ps:
551  case Intrinsic::x86_sse2_loadu_pd:
552  case Intrinsic::x86_sse2_loadu_dq:
553    // Turn PPC lvx     -> load if the pointer is known aligned.
554    // Turn X86 loadups -> load if the pointer is known aligned.
555    if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
556      Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
557                                         PointerType::getUnqual(II->getType()));
558      return new LoadInst(Ptr);
559    }
560    break;
561  case Intrinsic::ppc_altivec_stvx:
562  case Intrinsic::ppc_altivec_stvxl:
563    // Turn stvx -> store if the pointer is known aligned.
564    if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
565      const Type *OpPtrTy =
566        PointerType::getUnqual(II->getOperand(1)->getType());
567      Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
568      return new StoreInst(II->getOperand(1), Ptr);
569    }
570    break;
571  case Intrinsic::x86_sse_storeu_ps:
572  case Intrinsic::x86_sse2_storeu_pd:
573  case Intrinsic::x86_sse2_storeu_dq:
574    // Turn X86 storeu -> store if the pointer is known aligned.
575    if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
576      const Type *OpPtrTy =
577        PointerType::getUnqual(II->getOperand(2)->getType());
578      Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
579      return new StoreInst(II->getOperand(2), Ptr);
580    }
581    break;
582
583  case Intrinsic::x86_sse_cvttss2si: {
584    // These intrinsics only demands the 0th element of its input vector.  If
585    // we can simplify the input based on that, do so now.
586    unsigned VWidth =
587      cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
588    APInt DemandedElts(VWidth, 1);
589    APInt UndefElts(VWidth, 0);
590    if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
591                                              UndefElts)) {
592      II->setOperand(1, V);
593      return II;
594    }
595    break;
596  }
597
598  case Intrinsic::ppc_altivec_vperm:
599    // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
600    if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
601      assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
602
603      // Check that all of the elements are integer constants or undefs.
604      bool AllEltsOk = true;
605      for (unsigned i = 0; i != 16; ++i) {
606        if (!isa<ConstantInt>(Mask->getOperand(i)) &&
607            !isa<UndefValue>(Mask->getOperand(i))) {
608          AllEltsOk = false;
609          break;
610        }
611      }
612
613      if (AllEltsOk) {
614        // Cast the input vectors to byte vectors.
615        Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
616        Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
617        Value *Result = UndefValue::get(Op0->getType());
618
619        // Only extract each element once.
620        Value *ExtractedElts[32];
621        memset(ExtractedElts, 0, sizeof(ExtractedElts));
622
623        for (unsigned i = 0; i != 16; ++i) {
624          if (isa<UndefValue>(Mask->getOperand(i)))
625            continue;
626          unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
627          Idx &= 31;  // Match the hardware behavior.
628
629          if (ExtractedElts[Idx] == 0) {
630            ExtractedElts[Idx] =
631              Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
632                  ConstantInt::get(Type::getInt32Ty(II->getContext()),
633                                   Idx&15, false), "tmp");
634          }
635
636          // Insert this value into the result vector.
637          Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
638                         ConstantInt::get(Type::getInt32Ty(II->getContext()),
639                                          i, false), "tmp");
640        }
641        return CastInst::Create(Instruction::BitCast, Result, CI.getType());
642      }
643    }
644    break;
645
646  case Intrinsic::stackrestore: {
647    // If the save is right next to the restore, remove the restore.  This can
648    // happen when variable allocas are DCE'd.
649    if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
650      if (SS->getIntrinsicID() == Intrinsic::stacksave) {
651        BasicBlock::iterator BI = SS;
652        if (&*++BI == II)
653          return EraseInstFromFunction(CI);
654      }
655    }
656
657    // Scan down this block to see if there is another stack restore in the
658    // same block without an intervening call/alloca.
659    BasicBlock::iterator BI = II;
660    TerminatorInst *TI = II->getParent()->getTerminator();
661    bool CannotRemove = false;
662    for (++BI; &*BI != TI; ++BI) {
663      if (isa<AllocaInst>(BI) || isMalloc(BI)) {
664        CannotRemove = true;
665        break;
666      }
667      if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
668        if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
669          // If there is a stackrestore below this one, remove this one.
670          if (II->getIntrinsicID() == Intrinsic::stackrestore)
671            return EraseInstFromFunction(CI);
672          // Otherwise, ignore the intrinsic.
673        } else {
674          // If we found a non-intrinsic call, we can't remove the stack
675          // restore.
676          CannotRemove = true;
677          break;
678        }
679      }
680    }
681
682    // If the stack restore is in a return/unwind block and if there are no
683    // allocas or calls between the restore and the return, nuke the restore.
684    if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
685      return EraseInstFromFunction(CI);
686    break;
687  }
688  }
689
690  return visitCallSite(II);
691}
692
693// InvokeInst simplification
694//
695Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
696  return visitCallSite(&II);
697}
698
699/// isSafeToEliminateVarargsCast - If this cast does not affect the value
700/// passed through the varargs area, we can eliminate the use of the cast.
701static bool isSafeToEliminateVarargsCast(const CallSite CS,
702                                         const CastInst * const CI,
703                                         const TargetData * const TD,
704                                         const int ix) {
705  if (!CI->isLosslessCast())
706    return false;
707
708  // The size of ByVal arguments is derived from the type, so we
709  // can't change to a type with a different size.  If the size were
710  // passed explicitly we could avoid this check.
711  if (!CS.paramHasAttr(ix, Attribute::ByVal))
712    return true;
713
714  const Type* SrcTy =
715            cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
716  const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
717  if (!SrcTy->isSized() || !DstTy->isSized())
718    return false;
719  if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
720    return false;
721  return true;
722}
723
724// visitCallSite - Improvements for call and invoke instructions.
725//
726Instruction *InstCombiner::visitCallSite(CallSite CS) {
727  bool Changed = false;
728
729  // If the callee is a constexpr cast of a function, attempt to move the cast
730  // to the arguments of the call/invoke.
731  if (transformConstExprCastCall(CS)) return 0;
732
733  Value *Callee = CS.getCalledValue();
734
735  if (Function *CalleeF = dyn_cast<Function>(Callee))
736    // If the call and callee calling conventions don't match, this call must
737    // be unreachable, as the call is undefined.
738    if (CalleeF->getCallingConv() != CS.getCallingConv() &&
739        // Only do this for calls to a function with a body.  A prototype may
740        // not actually end up matching the implementation's calling conv for a
741        // variety of reasons (e.g. it may be written in assembly).
742        !CalleeF->isDeclaration()) {
743      Instruction *OldCall = CS.getInstruction();
744      new StoreInst(ConstantInt::getTrue(Callee->getContext()),
745                UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
746                                  OldCall);
747      // If OldCall dues not return void then replaceAllUsesWith undef.
748      // This allows ValueHandlers and custom metadata to adjust itself.
749      if (!OldCall->getType()->isVoidTy())
750        OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
751      if (isa<CallInst>(OldCall))
752        return EraseInstFromFunction(*OldCall);
753
754      // We cannot remove an invoke, because it would change the CFG, just
755      // change the callee to a null pointer.
756      cast<InvokeInst>(OldCall)->setOperand(0,
757                                    Constant::getNullValue(CalleeF->getType()));
758      return 0;
759    }
760
761  if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
762    // This instruction is not reachable, just remove it.  We insert a store to
763    // undef so that we know that this code is not reachable, despite the fact
764    // that we can't modify the CFG here.
765    new StoreInst(ConstantInt::getTrue(Callee->getContext()),
766               UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
767                  CS.getInstruction());
768
769    // If CS dues not return void then replaceAllUsesWith undef.
770    // This allows ValueHandlers and custom metadata to adjust itself.
771    if (!CS.getInstruction()->getType()->isVoidTy())
772      CS.getInstruction()->
773        replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
774
775    if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
776      // Don't break the CFG, insert a dummy cond branch.
777      BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
778                         ConstantInt::getTrue(Callee->getContext()), II);
779    }
780    return EraseInstFromFunction(*CS.getInstruction());
781  }
782
783  if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
784    if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
785      if (In->getIntrinsicID() == Intrinsic::init_trampoline)
786        return transformCallThroughTrampoline(CS);
787
788  const PointerType *PTy = cast<PointerType>(Callee->getType());
789  const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
790  if (FTy->isVarArg()) {
791    int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
792    // See if we can optimize any arguments passed through the varargs area of
793    // the call.
794    for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
795           E = CS.arg_end(); I != E; ++I, ++ix) {
796      CastInst *CI = dyn_cast<CastInst>(*I);
797      if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
798        *I = CI->getOperand(0);
799        Changed = true;
800      }
801    }
802  }
803
804  if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
805    // Inline asm calls cannot throw - mark them 'nounwind'.
806    CS.setDoesNotThrow();
807    Changed = true;
808  }
809
810  return Changed ? CS.getInstruction() : 0;
811}
812
813// transformConstExprCastCall - If the callee is a constexpr cast of a function,
814// attempt to move the cast to the arguments of the call/invoke.
815//
816bool InstCombiner::transformConstExprCastCall(CallSite CS) {
817  if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
818  ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
819  if (CE->getOpcode() != Instruction::BitCast ||
820      !isa<Function>(CE->getOperand(0)))
821    return false;
822  Function *Callee = cast<Function>(CE->getOperand(0));
823  Instruction *Caller = CS.getInstruction();
824  const AttrListPtr &CallerPAL = CS.getAttributes();
825
826  // Okay, this is a cast from a function to a different type.  Unless doing so
827  // would cause a type conversion of one of our arguments, change this call to
828  // be a direct call with arguments casted to the appropriate types.
829  //
830  const FunctionType *FT = Callee->getFunctionType();
831  const Type *OldRetTy = Caller->getType();
832  const Type *NewRetTy = FT->getReturnType();
833
834  if (NewRetTy->isStructTy())
835    return false; // TODO: Handle multiple return values.
836
837  // Check to see if we are changing the return type...
838  if (OldRetTy != NewRetTy) {
839    if (Callee->isDeclaration() &&
840        // Conversion is ok if changing from one pointer type to another or from
841        // a pointer to an integer of the same size.
842        !((OldRetTy->isPointerTy() || !TD ||
843           OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
844          (NewRetTy->isPointerTy() || !TD ||
845           NewRetTy == TD->getIntPtrType(Caller->getContext()))))
846      return false;   // Cannot transform this return value.
847
848    if (!Caller->use_empty() &&
849        // void -> non-void is handled specially
850        !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
851      return false;   // Cannot transform this return value.
852
853    if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
854      Attributes RAttrs = CallerPAL.getRetAttributes();
855      if (RAttrs & Attribute::typeIncompatible(NewRetTy))
856        return false;   // Attribute not compatible with transformed value.
857    }
858
859    // If the callsite is an invoke instruction, and the return value is used by
860    // a PHI node in a successor, we cannot change the return type of the call
861    // because there is no place to put the cast instruction (without breaking
862    // the critical edge).  Bail out in this case.
863    if (!Caller->use_empty())
864      if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
865        for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
866             UI != E; ++UI)
867          if (PHINode *PN = dyn_cast<PHINode>(*UI))
868            if (PN->getParent() == II->getNormalDest() ||
869                PN->getParent() == II->getUnwindDest())
870              return false;
871  }
872
873  unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
874  unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
875
876  CallSite::arg_iterator AI = CS.arg_begin();
877  for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
878    const Type *ParamTy = FT->getParamType(i);
879    const Type *ActTy = (*AI)->getType();
880
881    if (!CastInst::isCastable(ActTy, ParamTy))
882      return false;   // Cannot transform this parameter value.
883
884    if (CallerPAL.getParamAttributes(i + 1)
885        & Attribute::typeIncompatible(ParamTy))
886      return false;   // Attribute not compatible with transformed value.
887
888    // Converting from one pointer type to another or between a pointer and an
889    // integer of the same size is safe even if we do not have a body.
890    bool isConvertible = ActTy == ParamTy ||
891      (TD && ((ParamTy->isPointerTy() ||
892      ParamTy == TD->getIntPtrType(Caller->getContext())) &&
893              (ActTy->isPointerTy() ||
894              ActTy == TD->getIntPtrType(Caller->getContext()))));
895    if (Callee->isDeclaration() && !isConvertible) return false;
896  }
897
898  if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
899      Callee->isDeclaration())
900    return false;   // Do not delete arguments unless we have a function body.
901
902  if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
903      !CallerPAL.isEmpty())
904    // In this case we have more arguments than the new function type, but we
905    // won't be dropping them.  Check that these extra arguments have attributes
906    // that are compatible with being a vararg call argument.
907    for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
908      if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
909        break;
910      Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
911      if (PAttrs & Attribute::VarArgsIncompatible)
912        return false;
913    }
914
915  // Okay, we decided that this is a safe thing to do: go ahead and start
916  // inserting cast instructions as necessary...
917  std::vector<Value*> Args;
918  Args.reserve(NumActualArgs);
919  SmallVector<AttributeWithIndex, 8> attrVec;
920  attrVec.reserve(NumCommonArgs);
921
922  // Get any return attributes.
923  Attributes RAttrs = CallerPAL.getRetAttributes();
924
925  // If the return value is not being used, the type may not be compatible
926  // with the existing attributes.  Wipe out any problematic attributes.
927  RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
928
929  // Add the new return attributes.
930  if (RAttrs)
931    attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
932
933  AI = CS.arg_begin();
934  for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
935    const Type *ParamTy = FT->getParamType(i);
936    if ((*AI)->getType() == ParamTy) {
937      Args.push_back(*AI);
938    } else {
939      Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
940          false, ParamTy, false);
941      Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
942    }
943
944    // Add any parameter attributes.
945    if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
946      attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
947  }
948
949  // If the function takes more arguments than the call was taking, add them
950  // now.
951  for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
952    Args.push_back(Constant::getNullValue(FT->getParamType(i)));
953
954  // If we are removing arguments to the function, emit an obnoxious warning.
955  if (FT->getNumParams() < NumActualArgs) {
956    if (!FT->isVarArg()) {
957      errs() << "WARNING: While resolving call to function '"
958             << Callee->getName() << "' arguments were dropped!\n";
959    } else {
960      // Add all of the arguments in their promoted form to the arg list.
961      for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
962        const Type *PTy = getPromotedType((*AI)->getType());
963        if (PTy != (*AI)->getType()) {
964          // Must promote to pass through va_arg area!
965          Instruction::CastOps opcode =
966            CastInst::getCastOpcode(*AI, false, PTy, false);
967          Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
968        } else {
969          Args.push_back(*AI);
970        }
971
972        // Add any parameter attributes.
973        if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
974          attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
975      }
976    }
977  }
978
979  if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
980    attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
981
982  if (NewRetTy->isVoidTy())
983    Caller->setName("");   // Void type should not have a name.
984
985  const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
986                                                     attrVec.end());
987
988  Instruction *NC;
989  if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
990    NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
991                            Args.begin(), Args.end(),
992                            Caller->getName(), Caller);
993    cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
994    cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
995  } else {
996    NC = CallInst::Create(Callee, Args.begin(), Args.end(),
997                          Caller->getName(), Caller);
998    CallInst *CI = cast<CallInst>(Caller);
999    if (CI->isTailCall())
1000      cast<CallInst>(NC)->setTailCall();
1001    cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
1002    cast<CallInst>(NC)->setAttributes(NewCallerPAL);
1003  }
1004
1005  // Insert a cast of the return type as necessary.
1006  Value *NV = NC;
1007  if (OldRetTy != NV->getType() && !Caller->use_empty()) {
1008    if (!NV->getType()->isVoidTy()) {
1009      Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
1010                                                            OldRetTy, false);
1011      NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
1012
1013      // If this is an invoke instruction, we should insert it after the first
1014      // non-phi, instruction in the normal successor block.
1015      if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1016        BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
1017        InsertNewInstBefore(NC, *I);
1018      } else {
1019        // Otherwise, it's a call, just insert cast right after the call instr
1020        InsertNewInstBefore(NC, *Caller);
1021      }
1022      Worklist.AddUsersToWorkList(*Caller);
1023    } else {
1024      NV = UndefValue::get(Caller->getType());
1025    }
1026  }
1027
1028
1029  if (!Caller->use_empty())
1030    Caller->replaceAllUsesWith(NV);
1031
1032  EraseInstFromFunction(*Caller);
1033  return true;
1034}
1035
1036// transformCallThroughTrampoline - Turn a call to a function created by the
1037// init_trampoline intrinsic into a direct call to the underlying function.
1038//
1039Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
1040  Value *Callee = CS.getCalledValue();
1041  const PointerType *PTy = cast<PointerType>(Callee->getType());
1042  const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1043  const AttrListPtr &Attrs = CS.getAttributes();
1044
1045  // If the call already has the 'nest' attribute somewhere then give up -
1046  // otherwise 'nest' would occur twice after splicing in the chain.
1047  if (Attrs.hasAttrSomewhere(Attribute::Nest))
1048    return 0;
1049
1050  IntrinsicInst *Tramp =
1051    cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
1052
1053  Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
1054  const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
1055  const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
1056
1057  const AttrListPtr &NestAttrs = NestF->getAttributes();
1058  if (!NestAttrs.isEmpty()) {
1059    unsigned NestIdx = 1;
1060    const Type *NestTy = 0;
1061    Attributes NestAttr = Attribute::None;
1062
1063    // Look for a parameter marked with the 'nest' attribute.
1064    for (FunctionType::param_iterator I = NestFTy->param_begin(),
1065         E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
1066      if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
1067        // Record the parameter type and any other attributes.
1068        NestTy = *I;
1069        NestAttr = NestAttrs.getParamAttributes(NestIdx);
1070        break;
1071      }
1072
1073    if (NestTy) {
1074      Instruction *Caller = CS.getInstruction();
1075      std::vector<Value*> NewArgs;
1076      NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
1077
1078      SmallVector<AttributeWithIndex, 8> NewAttrs;
1079      NewAttrs.reserve(Attrs.getNumSlots() + 1);
1080
1081      // Insert the nest argument into the call argument list, which may
1082      // mean appending it.  Likewise for attributes.
1083
1084      // Add any result attributes.
1085      if (Attributes Attr = Attrs.getRetAttributes())
1086        NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
1087
1088      {
1089        unsigned Idx = 1;
1090        CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1091        do {
1092          if (Idx == NestIdx) {
1093            // Add the chain argument and attributes.
1094            Value *NestVal = Tramp->getOperand(3);
1095            if (NestVal->getType() != NestTy)
1096              NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
1097            NewArgs.push_back(NestVal);
1098            NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
1099          }
1100
1101          if (I == E)
1102            break;
1103
1104          // Add the original argument and attributes.
1105          NewArgs.push_back(*I);
1106          if (Attributes Attr = Attrs.getParamAttributes(Idx))
1107            NewAttrs.push_back
1108              (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
1109
1110          ++Idx, ++I;
1111        } while (1);
1112      }
1113
1114      // Add any function attributes.
1115      if (Attributes Attr = Attrs.getFnAttributes())
1116        NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
1117
1118      // The trampoline may have been bitcast to a bogus type (FTy).
1119      // Handle this by synthesizing a new function type, equal to FTy
1120      // with the chain parameter inserted.
1121
1122      std::vector<const Type*> NewTypes;
1123      NewTypes.reserve(FTy->getNumParams()+1);
1124
1125      // Insert the chain's type into the list of parameter types, which may
1126      // mean appending it.
1127      {
1128        unsigned Idx = 1;
1129        FunctionType::param_iterator I = FTy->param_begin(),
1130          E = FTy->param_end();
1131
1132        do {
1133          if (Idx == NestIdx)
1134            // Add the chain's type.
1135            NewTypes.push_back(NestTy);
1136
1137          if (I == E)
1138            break;
1139
1140          // Add the original type.
1141          NewTypes.push_back(*I);
1142
1143          ++Idx, ++I;
1144        } while (1);
1145      }
1146
1147      // Replace the trampoline call with a direct call.  Let the generic
1148      // code sort out any function type mismatches.
1149      FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
1150                                                FTy->isVarArg());
1151      Constant *NewCallee =
1152        NestF->getType() == PointerType::getUnqual(NewFTy) ?
1153        NestF : ConstantExpr::getBitCast(NestF,
1154                                         PointerType::getUnqual(NewFTy));
1155      const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
1156                                                   NewAttrs.end());
1157
1158      Instruction *NewCaller;
1159      if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1160        NewCaller = InvokeInst::Create(NewCallee,
1161                                       II->getNormalDest(), II->getUnwindDest(),
1162                                       NewArgs.begin(), NewArgs.end(),
1163                                       Caller->getName(), Caller);
1164        cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
1165        cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
1166      } else {
1167        NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
1168                                     Caller->getName(), Caller);
1169        if (cast<CallInst>(Caller)->isTailCall())
1170          cast<CallInst>(NewCaller)->setTailCall();
1171        cast<CallInst>(NewCaller)->
1172          setCallingConv(cast<CallInst>(Caller)->getCallingConv());
1173        cast<CallInst>(NewCaller)->setAttributes(NewPAL);
1174      }
1175      if (!Caller->getType()->isVoidTy())
1176        Caller->replaceAllUsesWith(NewCaller);
1177      Caller->eraseFromParent();
1178      Worklist.Remove(Caller);
1179      return 0;
1180    }
1181  }
1182
1183  // Replace the trampoline call with a direct call.  Since there is no 'nest'
1184  // parameter, there is no need to adjust the argument list.  Let the generic
1185  // code sort out any function type mismatches.
1186  Constant *NewCallee =
1187    NestF->getType() == PTy ? NestF :
1188                              ConstantExpr::getBitCast(NestF, PTy);
1189  CS.setCalledFunction(NewCallee);
1190  return CS.getInstruction();
1191}
1192
1193