More templatization.
[oota-llvm.git] / lib / CodeGen / IntrinsicLowering.cpp
1 //===-- IntrinsicLowering.cpp - Intrinsic Lowering default implementation -===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the IntrinsicLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Constants.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/Module.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/Type.h"
19 #include "llvm/CodeGen/IntrinsicLowering.h"
20 #include "llvm/Support/Streams.h"
21 #include "llvm/Target/TargetData.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/STLExtras.h"
24 using namespace llvm;
25
26 template <class ArgIt>
27 static void EnsureFunctionExists(Module &M, const char *Name,
28                                  ArgIt ArgBegin, ArgIt ArgEnd,
29                                  const Type *RetTy) {
30   // Insert a correctly-typed definition now.
31   std::vector<const Type *> ParamTys;
32   for (ArgIt I = ArgBegin; I != ArgEnd; ++I)
33     ParamTys.push_back(I->getType());
34   M.getOrInsertFunction(Name, FunctionType::get(RetTy, ParamTys, false));
35 }
36
37 /// ReplaceCallWith - This function is used when we want to lower an intrinsic
38 /// call to a call of an external function.  This handles hard cases such as
39 /// when there was already a prototype for the external function, and if that
40 /// prototype doesn't match the arguments we expect to pass in.
41 template <class ArgIt>
42 static CallInst *ReplaceCallWith(const char *NewFn, CallInst *CI,
43                                  ArgIt ArgBegin, ArgIt ArgEnd,
44                                  const Type *RetTy, Constant *&FCache) {
45   if (!FCache) {
46     // If we haven't already looked up this function, check to see if the
47     // program already contains a function with this name.
48     Module *M = CI->getParent()->getParent()->getParent();
49     // Get or insert the definition now.
50     std::vector<const Type *> ParamTys;
51     for (ArgIt I = ArgBegin; I != ArgEnd; ++I)
52       ParamTys.push_back((*I)->getType());
53     FCache = M->getOrInsertFunction(NewFn,
54                                     FunctionType::get(RetTy, ParamTys, false));
55   }
56
57   SmallVector<Value *, 8> Args(ArgBegin, ArgEnd);
58   CallInst *NewCI = new CallInst(FCache, Args.begin(), Args.end(),
59                                  CI->getName(), CI);
60   if (!CI->use_empty())
61     CI->replaceAllUsesWith(NewCI);
62   return NewCI;
63 }
64
65 void IntrinsicLowering::AddPrototypes(Module &M) {
66   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
67     if (I->isDeclaration() && !I->use_empty())
68       switch (I->getIntrinsicID()) {
69       default: break;
70       case Intrinsic::setjmp:
71         EnsureFunctionExists(M, "setjmp", I->arg_begin(), I->arg_end(),
72                              Type::Int32Ty);
73         break;
74       case Intrinsic::longjmp:
75         EnsureFunctionExists(M, "longjmp", I->arg_begin(), I->arg_end(),
76                              Type::VoidTy);
77         break;
78       case Intrinsic::siglongjmp:
79         EnsureFunctionExists(M, "abort", I->arg_end(), I->arg_end(),
80                              Type::VoidTy);
81         break;
82       case Intrinsic::memcpy_i32:
83       case Intrinsic::memcpy_i64:
84         M.getOrInsertFunction("memcpy", PointerType::get(Type::Int8Ty),
85                               PointerType::get(Type::Int8Ty), 
86                               PointerType::get(Type::Int8Ty), 
87                               TD.getIntPtrType(), (Type *)0);
88         break;
89       case Intrinsic::memmove_i32:
90       case Intrinsic::memmove_i64:
91         M.getOrInsertFunction("memmove", PointerType::get(Type::Int8Ty),
92                               PointerType::get(Type::Int8Ty), 
93                               PointerType::get(Type::Int8Ty), 
94                               TD.getIntPtrType(), (Type *)0);
95         break;
96       case Intrinsic::memset_i32:
97       case Intrinsic::memset_i64:
98         M.getOrInsertFunction("memset", PointerType::get(Type::Int8Ty),
99                               PointerType::get(Type::Int8Ty), Type::Int32Ty, 
100                               TD.getIntPtrType(), (Type *)0);
101         break;
102       case Intrinsic::sqrt:
103         switch((int)I->arg_begin()->getType()->getTypeID()) {
104         case Type::FloatTyID:
105           EnsureFunctionExists(M, "sqrtf", I->arg_begin(), I->arg_end(),
106                                Type::FloatTy);
107         case Type::DoubleTyID:
108           EnsureFunctionExists(M, "sqrt", I->arg_begin(), I->arg_end(),
109                                Type::DoubleTy);
110         case Type::X86_FP80TyID:
111         case Type::FP128TyID:
112         case Type::PPC_FP128TyID:
113           EnsureFunctionExists(M, "sqrtl", I->arg_begin(), I->arg_end(),
114                                I->arg_begin()->getType());
115         }
116         break;
117       case Intrinsic::sin:
118         switch((int)I->arg_begin()->getType()->getTypeID()) {
119         case Type::FloatTyID:
120           EnsureFunctionExists(M, "sinf", I->arg_begin(), I->arg_end(),
121                                Type::FloatTy);
122         case Type::DoubleTyID:
123           EnsureFunctionExists(M, "sin", I->arg_begin(), I->arg_end(),
124                                Type::DoubleTy);
125         case Type::X86_FP80TyID:
126         case Type::FP128TyID:
127         case Type::PPC_FP128TyID:
128           EnsureFunctionExists(M, "sinl", I->arg_begin(), I->arg_end(),
129                                I->arg_begin()->getType());
130         }
131         break;
132       case Intrinsic::cos:
133         switch((int)I->arg_begin()->getType()->getTypeID()) {
134         case Type::FloatTyID:
135           EnsureFunctionExists(M, "cosf", I->arg_begin(), I->arg_end(),
136                                Type::FloatTy);
137         case Type::DoubleTyID:
138           EnsureFunctionExists(M, "cos", I->arg_begin(), I->arg_end(),
139                                Type::DoubleTy);
140         case Type::X86_FP80TyID:
141         case Type::FP128TyID:
142         case Type::PPC_FP128TyID:
143           EnsureFunctionExists(M, "cosl", I->arg_begin(), I->arg_end(),
144                                I->arg_begin()->getType());
145         }
146         break;
147       case Intrinsic::pow:
148         switch((int)I->arg_begin()->getType()->getTypeID()) {
149         case Type::FloatTyID:
150           EnsureFunctionExists(M, "powf", I->arg_begin(), I->arg_end(),
151                                Type::FloatTy);
152         case Type::DoubleTyID:
153           EnsureFunctionExists(M, "pow", I->arg_begin(), I->arg_end(),
154                                Type::DoubleTy);
155         case Type::X86_FP80TyID:
156         case Type::FP128TyID:
157         case Type::PPC_FP128TyID:
158           EnsureFunctionExists(M, "powl", I->arg_begin(), I->arg_end(),
159                                I->arg_begin()->getType());
160         }
161         break;
162       }
163 }
164
165 /// LowerBSWAP - Emit the code to lower bswap of V before the specified
166 /// instruction IP.
167 static Value *LowerBSWAP(Value *V, Instruction *IP) {
168   assert(V->getType()->isInteger() && "Can't bswap a non-integer type!");
169
170   unsigned BitSize = V->getType()->getPrimitiveSizeInBits();
171   
172   switch(BitSize) {
173   default: assert(0 && "Unhandled type size of value to byteswap!");
174   case 16: {
175     Value *Tmp1 = BinaryOperator::createShl(V,
176                                 ConstantInt::get(V->getType(),8),"bswap.2",IP);
177     Value *Tmp2 = BinaryOperator::createLShr(V,
178                                 ConstantInt::get(V->getType(),8),"bswap.1",IP);
179     V = BinaryOperator::createOr(Tmp1, Tmp2, "bswap.i16", IP);
180     break;
181   }
182   case 32: {
183     Value *Tmp4 = BinaryOperator::createShl(V,
184                               ConstantInt::get(V->getType(),24),"bswap.4", IP);
185     Value *Tmp3 = BinaryOperator::createShl(V,
186                               ConstantInt::get(V->getType(),8),"bswap.3",IP);
187     Value *Tmp2 = BinaryOperator::createLShr(V,
188                               ConstantInt::get(V->getType(),8),"bswap.2",IP);
189     Value *Tmp1 = BinaryOperator::createLShr(V,
190                               ConstantInt::get(V->getType(),24),"bswap.1", IP);
191     Tmp3 = BinaryOperator::createAnd(Tmp3, 
192                                      ConstantInt::get(Type::Int32Ty, 0xFF0000),
193                                      "bswap.and3", IP);
194     Tmp2 = BinaryOperator::createAnd(Tmp2, 
195                                      ConstantInt::get(Type::Int32Ty, 0xFF00),
196                                      "bswap.and2", IP);
197     Tmp4 = BinaryOperator::createOr(Tmp4, Tmp3, "bswap.or1", IP);
198     Tmp2 = BinaryOperator::createOr(Tmp2, Tmp1, "bswap.or2", IP);
199     V = BinaryOperator::createOr(Tmp4, Tmp2, "bswap.i32", IP);
200     break;
201   }
202   case 64: {
203     Value *Tmp8 = BinaryOperator::createShl(V,
204                               ConstantInt::get(V->getType(),56),"bswap.8", IP);
205     Value *Tmp7 = BinaryOperator::createShl(V,
206                               ConstantInt::get(V->getType(),40),"bswap.7", IP);
207     Value *Tmp6 = BinaryOperator::createShl(V,
208                               ConstantInt::get(V->getType(),24),"bswap.6", IP);
209     Value *Tmp5 = BinaryOperator::createShl(V,
210                               ConstantInt::get(V->getType(),8),"bswap.5", IP);
211     Value* Tmp4 = BinaryOperator::createLShr(V,
212                               ConstantInt::get(V->getType(),8),"bswap.4", IP);
213     Value* Tmp3 = BinaryOperator::createLShr(V,
214                               ConstantInt::get(V->getType(),24),"bswap.3", IP);
215     Value* Tmp2 = BinaryOperator::createLShr(V,
216                               ConstantInt::get(V->getType(),40),"bswap.2", IP);
217     Value* Tmp1 = BinaryOperator::createLShr(V,
218                               ConstantInt::get(V->getType(),56),"bswap.1", IP);
219     Tmp7 = BinaryOperator::createAnd(Tmp7,
220                              ConstantInt::get(Type::Int64Ty, 
221                                0xFF000000000000ULL),
222                              "bswap.and7", IP);
223     Tmp6 = BinaryOperator::createAnd(Tmp6,
224                              ConstantInt::get(Type::Int64Ty, 0xFF0000000000ULL),
225                              "bswap.and6", IP);
226     Tmp5 = BinaryOperator::createAnd(Tmp5,
227                              ConstantInt::get(Type::Int64Ty, 0xFF00000000ULL),
228                              "bswap.and5", IP);
229     Tmp4 = BinaryOperator::createAnd(Tmp4,
230                              ConstantInt::get(Type::Int64Ty, 0xFF000000ULL),
231                              "bswap.and4", IP);
232     Tmp3 = BinaryOperator::createAnd(Tmp3,
233                              ConstantInt::get(Type::Int64Ty, 0xFF0000ULL),
234                              "bswap.and3", IP);
235     Tmp2 = BinaryOperator::createAnd(Tmp2,
236                              ConstantInt::get(Type::Int64Ty, 0xFF00ULL),
237                              "bswap.and2", IP);
238     Tmp8 = BinaryOperator::createOr(Tmp8, Tmp7, "bswap.or1", IP);
239     Tmp6 = BinaryOperator::createOr(Tmp6, Tmp5, "bswap.or2", IP);
240     Tmp4 = BinaryOperator::createOr(Tmp4, Tmp3, "bswap.or3", IP);
241     Tmp2 = BinaryOperator::createOr(Tmp2, Tmp1, "bswap.or4", IP);
242     Tmp8 = BinaryOperator::createOr(Tmp8, Tmp6, "bswap.or5", IP);
243     Tmp4 = BinaryOperator::createOr(Tmp4, Tmp2, "bswap.or6", IP);
244     V = BinaryOperator::createOr(Tmp8, Tmp4, "bswap.i64", IP);
245     break;
246   }
247   }
248   return V;
249 }
250
251 /// LowerCTPOP - Emit the code to lower ctpop of V before the specified
252 /// instruction IP.
253 static Value *LowerCTPOP(Value *V, Instruction *IP) {
254   assert(V->getType()->isInteger() && "Can't ctpop a non-integer type!");
255
256   static const uint64_t MaskValues[6] = {
257     0x5555555555555555ULL, 0x3333333333333333ULL,
258     0x0F0F0F0F0F0F0F0FULL, 0x00FF00FF00FF00FFULL,
259     0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL
260   };
261
262   unsigned BitSize = V->getType()->getPrimitiveSizeInBits();
263   unsigned WordSize = (BitSize + 63) / 64;
264   Value *Count = ConstantInt::get(V->getType(), 0);
265
266   for (unsigned n = 0; n < WordSize; ++n) {
267     Value *PartValue = V;
268     for (unsigned i = 1, ct = 0; i < (BitSize>64 ? 64 : BitSize); 
269          i <<= 1, ++ct) {
270       Value *MaskCst = ConstantInt::get(V->getType(), MaskValues[ct]);
271       Value *LHS = BinaryOperator::createAnd(
272                      PartValue, MaskCst, "cppop.and1", IP);
273       Value *VShift = BinaryOperator::createLShr(PartValue,
274                         ConstantInt::get(V->getType(), i), "ctpop.sh", IP);
275       Value *RHS = BinaryOperator::createAnd(VShift, MaskCst, "cppop.and2", IP);
276       PartValue = BinaryOperator::createAdd(LHS, RHS, "ctpop.step", IP);
277     }
278     Count = BinaryOperator::createAdd(PartValue, Count, "ctpop.part", IP);
279     if (BitSize > 64) {
280       V = BinaryOperator::createLShr(V, ConstantInt::get(V->getType(), 64), 
281                                      "ctpop.part.sh", IP);
282       BitSize -= 64;
283     }
284   }
285
286   return Count;
287 }
288
289 /// LowerCTLZ - Emit the code to lower ctlz of V before the specified
290 /// instruction IP.
291 static Value *LowerCTLZ(Value *V, Instruction *IP) {
292
293   unsigned BitSize = V->getType()->getPrimitiveSizeInBits();
294   for (unsigned i = 1; i < BitSize; i <<= 1) {
295     Value *ShVal = ConstantInt::get(V->getType(), i);
296     ShVal = BinaryOperator::createLShr(V, ShVal, "ctlz.sh", IP);
297     V = BinaryOperator::createOr(V, ShVal, "ctlz.step", IP);
298   }
299
300   V = BinaryOperator::createNot(V, "", IP);
301   return LowerCTPOP(V, IP);
302 }
303
304 /// Convert the llvm.part.select.iX.iY intrinsic. This intrinsic takes 
305 /// three integer arguments. The first argument is the Value from which the
306 /// bits will be selected. It may be of any bit width. The second and third
307 /// arguments specify a range of bits to select with the second argument 
308 /// specifying the low bit and the third argument specifying the high bit. Both
309 /// must be type i32. The result is the corresponding selected bits from the
310 /// Value in the same width as the Value (first argument). If the low bit index
311 /// is higher than the high bit index then the inverse selection is done and 
312 /// the bits are returned in inverse order. 
313 /// @brief Lowering of llvm.part.select intrinsic.
314 static Instruction *LowerPartSelect(CallInst *CI) {
315   // Make sure we're dealing with a part select intrinsic here
316   Function *F = CI->getCalledFunction();
317   const FunctionType *FT = F->getFunctionType();
318   if (!F->isDeclaration() || !FT->getReturnType()->isInteger() ||
319       FT->getNumParams() != 3 || !FT->getParamType(0)->isInteger() ||
320       !FT->getParamType(1)->isInteger() || !FT->getParamType(2)->isInteger())
321     return CI;
322
323   // Get the intrinsic implementation function by converting all the . to _
324   // in the intrinsic's function name and then reconstructing the function
325   // declaration.
326   std::string Name(F->getName());
327   for (unsigned i = 4; i < Name.length(); ++i)
328     if (Name[i] == '.')
329       Name[i] = '_';
330   Module* M = F->getParent();
331   F = cast<Function>(M->getOrInsertFunction(Name, FT));
332   F->setLinkage(GlobalValue::WeakLinkage);
333
334   // If we haven't defined the impl function yet, do so now
335   if (F->isDeclaration()) {
336
337     // Get the arguments to the function
338     Function::arg_iterator args = F->arg_begin();
339     Value* Val = args++; Val->setName("Val");
340     Value* Lo = args++; Lo->setName("Lo");
341     Value* Hi  = args++; Hi->setName("High");
342
343     // We want to select a range of bits here such that [Hi, Lo] is shifted
344     // down to the low bits. However, it is quite possible that Hi is smaller
345     // than Lo in which case the bits have to be reversed. 
346     
347     // Create the blocks we will need for the two cases (forward, reverse)
348     BasicBlock* CurBB   = new BasicBlock("entry", F);
349     BasicBlock *RevSize = new BasicBlock("revsize", CurBB->getParent());
350     BasicBlock *FwdSize = new BasicBlock("fwdsize", CurBB->getParent());
351     BasicBlock *Compute = new BasicBlock("compute", CurBB->getParent());
352     BasicBlock *Reverse = new BasicBlock("reverse", CurBB->getParent());
353     BasicBlock *RsltBlk = new BasicBlock("result",  CurBB->getParent());
354
355     // Cast Hi and Lo to the size of Val so the widths are all the same
356     if (Hi->getType() != Val->getType())
357       Hi = CastInst::createIntegerCast(Hi, Val->getType(), false, 
358                                          "tmp", CurBB);
359     if (Lo->getType() != Val->getType())
360       Lo = CastInst::createIntegerCast(Lo, Val->getType(), false, 
361                                           "tmp", CurBB);
362
363     // Compute a few things that both cases will need, up front.
364     Constant* Zero = ConstantInt::get(Val->getType(), 0);
365     Constant* One = ConstantInt::get(Val->getType(), 1);
366     Constant* AllOnes = ConstantInt::getAllOnesValue(Val->getType());
367
368     // Compare the Hi and Lo bit positions. This is used to determine 
369     // which case we have (forward or reverse)
370     ICmpInst *Cmp = new ICmpInst(ICmpInst::ICMP_ULT, Hi, Lo, "less",CurBB);
371     new BranchInst(RevSize, FwdSize, Cmp, CurBB);
372
373     // First, copmute the number of bits in the forward case.
374     Instruction* FBitSize = 
375       BinaryOperator::createSub(Hi, Lo,"fbits", FwdSize);
376     new BranchInst(Compute, FwdSize);
377
378     // Second, compute the number of bits in the reverse case.
379     Instruction* RBitSize = 
380       BinaryOperator::createSub(Lo, Hi, "rbits", RevSize);
381     new BranchInst(Compute, RevSize);
382
383     // Now, compute the bit range. Start by getting the bitsize and the shift
384     // amount (either Hi or Lo) from PHI nodes. Then we compute a mask for 
385     // the number of bits we want in the range. We shift the bits down to the 
386     // least significant bits, apply the mask to zero out unwanted high bits, 
387     // and we have computed the "forward" result. It may still need to be 
388     // reversed.
389
390     // Get the BitSize from one of the two subtractions
391     PHINode *BitSize = new PHINode(Val->getType(), "bits", Compute);
392     BitSize->reserveOperandSpace(2);
393     BitSize->addIncoming(FBitSize, FwdSize);
394     BitSize->addIncoming(RBitSize, RevSize);
395
396     // Get the ShiftAmount as the smaller of Hi/Lo
397     PHINode *ShiftAmt = new PHINode(Val->getType(), "shiftamt", Compute);
398     ShiftAmt->reserveOperandSpace(2);
399     ShiftAmt->addIncoming(Lo, FwdSize);
400     ShiftAmt->addIncoming(Hi, RevSize);
401
402     // Increment the bit size
403     Instruction *BitSizePlusOne = 
404       BinaryOperator::createAdd(BitSize, One, "bits", Compute);
405
406     // Create a Mask to zero out the high order bits.
407     Instruction* Mask = 
408       BinaryOperator::createShl(AllOnes, BitSizePlusOne, "mask", Compute);
409     Mask = BinaryOperator::createNot(Mask, "mask", Compute);
410
411     // Shift the bits down and apply the mask
412     Instruction* FRes = 
413       BinaryOperator::createLShr(Val, ShiftAmt, "fres", Compute);
414     FRes = BinaryOperator::createAnd(FRes, Mask, "fres", Compute);
415     new BranchInst(Reverse, RsltBlk, Cmp, Compute);
416
417     // In the Reverse block we have the mask already in FRes but we must reverse
418     // it by shifting FRes bits right and putting them in RRes by shifting them 
419     // in from left.
420
421     // First set up our loop counters
422     PHINode *Count = new PHINode(Val->getType(), "count", Reverse);
423     Count->reserveOperandSpace(2);
424     Count->addIncoming(BitSizePlusOne, Compute);
425
426     // Next, get the value that we are shifting.
427     PHINode *BitsToShift   = new PHINode(Val->getType(), "val", Reverse);
428     BitsToShift->reserveOperandSpace(2);
429     BitsToShift->addIncoming(FRes, Compute);
430
431     // Finally, get the result of the last computation
432     PHINode *RRes  = new PHINode(Val->getType(), "rres", Reverse);
433     RRes->reserveOperandSpace(2);
434     RRes->addIncoming(Zero, Compute);
435
436     // Decrement the counter
437     Instruction *Decr = BinaryOperator::createSub(Count, One, "decr", Reverse);
438     Count->addIncoming(Decr, Reverse);
439
440     // Compute the Bit that we want to move
441     Instruction *Bit = 
442       BinaryOperator::createAnd(BitsToShift, One, "bit", Reverse);
443
444     // Compute the new value for next iteration.
445     Instruction *NewVal = 
446       BinaryOperator::createLShr(BitsToShift, One, "rshift", Reverse);
447     BitsToShift->addIncoming(NewVal, Reverse);
448
449     // Shift the bit into the low bits of the result.
450     Instruction *NewRes = 
451       BinaryOperator::createShl(RRes, One, "lshift", Reverse);
452     NewRes = BinaryOperator::createOr(NewRes, Bit, "addbit", Reverse);
453     RRes->addIncoming(NewRes, Reverse);
454     
455     // Terminate loop if we've moved all the bits.
456     ICmpInst *Cond = 
457       new ICmpInst(ICmpInst::ICMP_EQ, Decr, Zero, "cond", Reverse);
458     new BranchInst(RsltBlk, Reverse, Cond, Reverse);
459
460     // Finally, in the result block, select one of the two results with a PHI
461     // node and return the result;
462     CurBB = RsltBlk;
463     PHINode *BitSelect = new PHINode(Val->getType(), "part_select", CurBB);
464     BitSelect->reserveOperandSpace(2);
465     BitSelect->addIncoming(FRes, Compute);
466     BitSelect->addIncoming(NewRes, Reverse);
467     new ReturnInst(BitSelect, CurBB);
468   }
469
470   // Return a call to the implementation function
471   Value *Args[] = {
472     CI->getOperand(1),
473     CI->getOperand(2),
474     CI->getOperand(3)
475   };
476   return new CallInst(F, Args, array_endof(Args), CI->getName(), CI);
477 }
478
479 /// Convert the llvm.part.set.iX.iY.iZ intrinsic. This intrinsic takes 
480 /// four integer arguments (iAny %Value, iAny %Replacement, i32 %Low, i32 %High)
481 /// The first two arguments can be any bit width. The result is the same width
482 /// as %Value. The operation replaces bits between %Low and %High with the value
483 /// in %Replacement. If %Replacement is not the same width, it is truncated or
484 /// zero extended as appropriate to fit the bits being replaced. If %Low is
485 /// greater than %High then the inverse set of bits are replaced.
486 /// @brief Lowering of llvm.bit.part.set intrinsic.
487 static Instruction *LowerPartSet(CallInst *CI) {
488   // Make sure we're dealing with a part select intrinsic here
489   Function *F = CI->getCalledFunction();
490   const FunctionType *FT = F->getFunctionType();
491   if (!F->isDeclaration() || !FT->getReturnType()->isInteger() ||
492       FT->getNumParams() != 4 || !FT->getParamType(0)->isInteger() ||
493       !FT->getParamType(1)->isInteger() || !FT->getParamType(2)->isInteger() ||
494       !FT->getParamType(3)->isInteger())
495     return CI;
496
497   // Get the intrinsic implementation function by converting all the . to _
498   // in the intrinsic's function name and then reconstructing the function
499   // declaration.
500   std::string Name(F->getName());
501   for (unsigned i = 4; i < Name.length(); ++i)
502     if (Name[i] == '.')
503       Name[i] = '_';
504   Module* M = F->getParent();
505   F = cast<Function>(M->getOrInsertFunction(Name, FT));
506   F->setLinkage(GlobalValue::WeakLinkage);
507
508   // If we haven't defined the impl function yet, do so now
509   if (F->isDeclaration()) {
510     // Get the arguments for the function.
511     Function::arg_iterator args = F->arg_begin();
512     Value* Val = args++; Val->setName("Val");
513     Value* Rep = args++; Rep->setName("Rep");
514     Value* Lo  = args++; Lo->setName("Lo");
515     Value* Hi  = args++; Hi->setName("Hi");
516
517     // Get some types we need
518     const IntegerType* ValTy = cast<IntegerType>(Val->getType());
519     const IntegerType* RepTy = cast<IntegerType>(Rep->getType());
520     uint32_t ValBits = ValTy->getBitWidth();
521     uint32_t RepBits = RepTy->getBitWidth();
522
523     // Constant Definitions
524     ConstantInt* RepBitWidth = ConstantInt::get(Type::Int32Ty, RepBits);
525     ConstantInt* RepMask = ConstantInt::getAllOnesValue(RepTy);
526     ConstantInt* ValMask = ConstantInt::getAllOnesValue(ValTy);
527     ConstantInt* One = ConstantInt::get(Type::Int32Ty, 1);
528     ConstantInt* ValOne = ConstantInt::get(ValTy, 1);
529     ConstantInt* Zero = ConstantInt::get(Type::Int32Ty, 0);
530     ConstantInt* ValZero = ConstantInt::get(ValTy, 0);
531
532     // Basic blocks we fill in below.
533     BasicBlock* entry = new BasicBlock("entry", F, 0);
534     BasicBlock* large = new BasicBlock("large", F, 0);
535     BasicBlock* small = new BasicBlock("small", F, 0);
536     BasicBlock* reverse = new BasicBlock("reverse", F, 0);
537     BasicBlock* result = new BasicBlock("result", F, 0);
538
539     // BASIC BLOCK: entry
540     // First, get the number of bits that we're placing as an i32
541     ICmpInst* is_forward = 
542       new ICmpInst(ICmpInst::ICMP_ULT, Lo, Hi, "", entry);
543     SelectInst* Hi_pn = new SelectInst(is_forward, Hi, Lo, "", entry);
544     SelectInst* Lo_pn = new SelectInst(is_forward, Lo, Hi, "", entry);
545     BinaryOperator* NumBits = BinaryOperator::createSub(Hi_pn, Lo_pn, "",entry);
546     NumBits = BinaryOperator::createAdd(NumBits, One, "", entry);
547     // Now, convert Lo and Hi to ValTy bit width
548     if (ValBits > 32) {
549       Lo = new ZExtInst(Lo_pn, ValTy, "", entry);
550     } else if (ValBits < 32) {
551       Lo = new TruncInst(Lo_pn, ValTy, "", entry);
552     }
553     // Determine if the replacement bits are larger than the number of bits we
554     // are replacing and deal with it.
555     ICmpInst* is_large = 
556       new ICmpInst(ICmpInst::ICMP_ULT, NumBits, RepBitWidth, "", entry);
557     new BranchInst(large, small, is_large, entry);
558
559     // BASIC BLOCK: large
560     Instruction* MaskBits = 
561       BinaryOperator::createSub(RepBitWidth, NumBits, "", large);
562     MaskBits = CastInst::createIntegerCast(MaskBits, RepMask->getType(), 
563                                            false, "", large);
564     BinaryOperator* Mask1 = 
565       BinaryOperator::createLShr(RepMask, MaskBits, "", large);
566     BinaryOperator* Rep2 = BinaryOperator::createAnd(Mask1, Rep, "", large);
567     new BranchInst(small, large);
568
569     // BASIC BLOCK: small
570     PHINode* Rep3 = new PHINode(RepTy, "", small);
571     Rep3->reserveOperandSpace(2);
572     Rep3->addIncoming(Rep2, large);
573     Rep3->addIncoming(Rep, entry);
574     Value* Rep4 = Rep3;
575     if (ValBits > RepBits)
576       Rep4 = new ZExtInst(Rep3, ValTy, "", small);
577     else if (ValBits < RepBits)
578       Rep4 = new TruncInst(Rep3, ValTy, "", small);
579     new BranchInst(result, reverse, is_forward, small);
580
581     // BASIC BLOCK: reverse (reverses the bits of the replacement)
582     // Set up our loop counter as a PHI so we can decrement on each iteration.
583     // We will loop for the number of bits in the replacement value.
584     PHINode *Count = new PHINode(Type::Int32Ty, "count", reverse);
585     Count->reserveOperandSpace(2);
586     Count->addIncoming(NumBits, small);
587
588     // Get the value that we are shifting bits out of as a PHI because
589     // we'll change this with each iteration.
590     PHINode *BitsToShift   = new PHINode(Val->getType(), "val", reverse);
591     BitsToShift->reserveOperandSpace(2);
592     BitsToShift->addIncoming(Rep4, small);
593
594     // Get the result of the last computation or zero on first iteration
595     PHINode *RRes  = new PHINode(Val->getType(), "rres", reverse);
596     RRes->reserveOperandSpace(2);
597     RRes->addIncoming(ValZero, small);
598
599     // Decrement the loop counter by one
600     Instruction *Decr = BinaryOperator::createSub(Count, One, "", reverse);
601     Count->addIncoming(Decr, reverse);
602
603     // Get the bit that we want to move into the result
604     Value *Bit = BinaryOperator::createAnd(BitsToShift, ValOne, "", reverse);
605
606     // Compute the new value of the bits to shift for the next iteration.
607     Value *NewVal = BinaryOperator::createLShr(BitsToShift, ValOne,"", reverse);
608     BitsToShift->addIncoming(NewVal, reverse);
609
610     // Shift the bit we extracted into the low bit of the result.
611     Instruction *NewRes = BinaryOperator::createShl(RRes, ValOne, "", reverse);
612     NewRes = BinaryOperator::createOr(NewRes, Bit, "", reverse);
613     RRes->addIncoming(NewRes, reverse);
614     
615     // Terminate loop if we've moved all the bits.
616     ICmpInst *Cond = new ICmpInst(ICmpInst::ICMP_EQ, Decr, Zero, "", reverse);
617     new BranchInst(result, reverse, Cond, reverse);
618
619     // BASIC BLOCK: result
620     PHINode *Rplcmnt  = new PHINode(Val->getType(), "", result);
621     Rplcmnt->reserveOperandSpace(2);
622     Rplcmnt->addIncoming(NewRes, reverse);
623     Rplcmnt->addIncoming(Rep4, small);
624     Value* t0   = CastInst::createIntegerCast(NumBits,ValTy,false,"",result);
625     Value* t1   = BinaryOperator::createShl(ValMask, Lo, "", result);
626     Value* t2   = BinaryOperator::createNot(t1, "", result);
627     Value* t3   = BinaryOperator::createShl(t1, t0, "", result);
628     Value* t4   = BinaryOperator::createOr(t2, t3, "", result);
629     Value* t5   = BinaryOperator::createAnd(t4, Val, "", result);
630     Value* t6   = BinaryOperator::createShl(Rplcmnt, Lo, "", result);
631     Value* Rslt = BinaryOperator::createOr(t5, t6, "part_set", result);
632     new ReturnInst(Rslt, result);
633   }
634
635   // Return a call to the implementation function
636   Value *Args[] = {
637     CI->getOperand(1),
638     CI->getOperand(2),
639     CI->getOperand(3),
640     CI->getOperand(4)
641   };
642   return new CallInst(F, Args, array_endof(Args), CI->getName(), CI);
643 }
644
645
646 void IntrinsicLowering::LowerIntrinsicCall(CallInst *CI) {
647   Function *Callee = CI->getCalledFunction();
648   assert(Callee && "Cannot lower an indirect call!");
649
650   switch (Callee->getIntrinsicID()) {
651   case Intrinsic::not_intrinsic:
652     cerr << "Cannot lower a call to a non-intrinsic function '"
653          << Callee->getName() << "'!\n";
654     abort();
655   default:
656     cerr << "Error: Code generator does not support intrinsic function '"
657          << Callee->getName() << "'!\n";
658     abort();
659
660     // The setjmp/longjmp intrinsics should only exist in the code if it was
661     // never optimized (ie, right out of the CFE), or if it has been hacked on
662     // by the lowerinvoke pass.  In both cases, the right thing to do is to
663     // convert the call to an explicit setjmp or longjmp call.
664   case Intrinsic::setjmp: {
665     static Constant *SetjmpFCache = 0;
666     Value *V = ReplaceCallWith("setjmp", CI, CI->op_begin()+1, CI->op_end(),
667                                Type::Int32Ty, SetjmpFCache);
668     if (CI->getType() != Type::VoidTy)
669       CI->replaceAllUsesWith(V);
670     break;
671   }
672   case Intrinsic::sigsetjmp:
673      if (CI->getType() != Type::VoidTy)
674        CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
675      break;
676
677   case Intrinsic::longjmp: {
678     static Constant *LongjmpFCache = 0;
679     ReplaceCallWith("longjmp", CI, CI->op_begin()+1, CI->op_end(),
680                     Type::VoidTy, LongjmpFCache);
681     break;
682   }
683
684   case Intrinsic::siglongjmp: {
685     // Insert the call to abort
686     static Constant *AbortFCache = 0;
687     ReplaceCallWith("abort", CI, CI->op_end(), CI->op_end(), 
688                     Type::VoidTy, AbortFCache);
689     break;
690   }
691   case Intrinsic::ctpop:
692     CI->replaceAllUsesWith(LowerCTPOP(CI->getOperand(1), CI));
693     break;
694
695   case Intrinsic::bswap:
696     CI->replaceAllUsesWith(LowerBSWAP(CI->getOperand(1), CI));
697     break;
698     
699   case Intrinsic::ctlz:
700     CI->replaceAllUsesWith(LowerCTLZ(CI->getOperand(1), CI));
701     break;
702
703   case Intrinsic::cttz: {
704     // cttz(x) -> ctpop(~X & (X-1))
705     Value *Src = CI->getOperand(1);
706     Value *NotSrc = BinaryOperator::createNot(Src, Src->getName()+".not", CI);
707     Value *SrcM1  = ConstantInt::get(Src->getType(), 1);
708     SrcM1 = BinaryOperator::createSub(Src, SrcM1, "", CI);
709     Src = LowerCTPOP(BinaryOperator::createAnd(NotSrc, SrcM1, "", CI), CI);
710     CI->replaceAllUsesWith(Src);
711     break;
712   }
713
714   case Intrinsic::part_select:
715     CI->replaceAllUsesWith(LowerPartSelect(CI));
716     break;
717
718   case Intrinsic::part_set:
719     CI->replaceAllUsesWith(LowerPartSet(CI));
720     break;
721
722   case Intrinsic::stacksave:
723   case Intrinsic::stackrestore: {
724     static bool Warned = false;
725     if (!Warned)
726       cerr << "WARNING: this target does not support the llvm.stack"
727            << (Callee->getIntrinsicID() == Intrinsic::stacksave ?
728                "save" : "restore") << " intrinsic.\n";
729     Warned = true;
730     if (Callee->getIntrinsicID() == Intrinsic::stacksave)
731       CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
732     break;
733   }
734     
735   case Intrinsic::returnaddress:
736   case Intrinsic::frameaddress:
737     cerr << "WARNING: this target does not support the llvm."
738          << (Callee->getIntrinsicID() == Intrinsic::returnaddress ?
739              "return" : "frame") << "address intrinsic.\n";
740     CI->replaceAllUsesWith(ConstantPointerNull::get(
741                                             cast<PointerType>(CI->getType())));
742     break;
743
744   case Intrinsic::prefetch:
745     break;    // Simply strip out prefetches on unsupported architectures
746
747   case Intrinsic::pcmarker:
748     break;    // Simply strip out pcmarker on unsupported architectures
749   case Intrinsic::readcyclecounter: {
750     cerr << "WARNING: this target does not support the llvm.readcyclecoun"
751          << "ter intrinsic.  It is being lowered to a constant 0\n";
752     CI->replaceAllUsesWith(ConstantInt::get(Type::Int64Ty, 0));
753     break;
754   }
755
756   case Intrinsic::dbg_stoppoint:
757   case Intrinsic::dbg_region_start:
758   case Intrinsic::dbg_region_end:
759   case Intrinsic::dbg_func_start:
760   case Intrinsic::dbg_declare:
761     break;    // Simply strip out debugging intrinsics
762
763   case Intrinsic::eh_exception:
764   case Intrinsic::eh_selector_i32:
765   case Intrinsic::eh_selector_i64:
766     CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
767     break;
768
769   case Intrinsic::eh_typeid_for_i32:
770   case Intrinsic::eh_typeid_for_i64:
771     // Return something different to eh_selector.
772     CI->replaceAllUsesWith(ConstantInt::get(CI->getType(), 1));
773     break;
774
775   case Intrinsic::var_annotation:
776     break;   // Strip out annotate intrinsic
777     
778   case Intrinsic::memcpy_i32:
779   case Intrinsic::memcpy_i64: {
780     static Constant *MemcpyFCache = 0;
781     Value *Size = CI->getOperand(3);
782     const Type *IntPtr = TD.getIntPtrType();
783     if (Size->getType()->getPrimitiveSizeInBits() <
784         IntPtr->getPrimitiveSizeInBits())
785       Size = new ZExtInst(Size, IntPtr, "", CI);
786     else if (Size->getType()->getPrimitiveSizeInBits() >
787              IntPtr->getPrimitiveSizeInBits())
788       Size = new TruncInst(Size, IntPtr, "", CI);
789     Value *Ops[3];
790     Ops[0] = CI->getOperand(1);
791     Ops[1] = CI->getOperand(2);
792     Ops[2] = Size;
793     ReplaceCallWith("memcpy", CI, Ops, Ops+3, CI->getOperand(1)->getType(),
794                     MemcpyFCache);
795     break;
796   }
797   case Intrinsic::memmove_i32: 
798   case Intrinsic::memmove_i64: {
799     static Constant *MemmoveFCache = 0;
800     Value *Size = CI->getOperand(3);
801     const Type *IntPtr = TD.getIntPtrType();
802     if (Size->getType()->getPrimitiveSizeInBits() <
803         IntPtr->getPrimitiveSizeInBits())
804       Size = new ZExtInst(Size, IntPtr, "", CI);
805     else if (Size->getType()->getPrimitiveSizeInBits() >
806              IntPtr->getPrimitiveSizeInBits())
807       Size = new TruncInst(Size, IntPtr, "", CI);
808     Value *Ops[3];
809     Ops[0] = CI->getOperand(1);
810     Ops[1] = CI->getOperand(2);
811     Ops[2] = Size;
812     ReplaceCallWith("memmove", CI, Ops, Ops+3, CI->getOperand(1)->getType(),
813                     MemmoveFCache);
814     break;
815   }
816   case Intrinsic::memset_i32:
817   case Intrinsic::memset_i64: {
818     static Constant *MemsetFCache = 0;
819     Value *Size = CI->getOperand(3);
820     const Type *IntPtr = TD.getIntPtrType();
821     if (Size->getType()->getPrimitiveSizeInBits() <
822         IntPtr->getPrimitiveSizeInBits())
823       Size = new ZExtInst(Size, IntPtr, "", CI);
824     else if (Size->getType()->getPrimitiveSizeInBits() >
825              IntPtr->getPrimitiveSizeInBits())
826       Size = new TruncInst(Size, IntPtr, "", CI);
827     Value *Ops[3];
828     Ops[0] = CI->getOperand(1);
829     // Extend the amount to i32.
830     Ops[1] = new ZExtInst(CI->getOperand(2), Type::Int32Ty, "", CI);
831     Ops[2] = Size;
832     ReplaceCallWith("memset", CI, Ops, Ops+3, CI->getOperand(1)->getType(),
833                     MemsetFCache);
834     break;
835   }
836   case Intrinsic::sqrt: {
837     static Constant *sqrtfFCache = 0;
838     static Constant *sqrtFCache = 0;
839     static Constant *sqrtLDCache = 0;
840     switch (CI->getOperand(1)->getType()->getTypeID()) {
841     default: assert(0 && "Invalid type in sqrt"); abort();
842     case Type::FloatTyID:
843       ReplaceCallWith("sqrtf", CI, CI->op_begin()+1, CI->op_end(),
844                     Type::FloatTy, sqrtfFCache);
845       break;
846     case Type::DoubleTyID:
847       ReplaceCallWith("sqrt", CI, CI->op_begin()+1, CI->op_end(),
848                     Type::DoubleTy, sqrtFCache);
849       break;
850     case Type::X86_FP80TyID:
851     case Type::FP128TyID:
852     case Type::PPC_FP128TyID:
853       ReplaceCallWith("sqrtl", CI, CI->op_begin()+1, CI->op_end(),
854                     CI->getOperand(1)->getType(), sqrtLDCache);
855       break;
856     }
857     break;
858   }
859   }
860
861   assert(CI->use_empty() &&
862          "Lowering should have eliminated any uses of the intrinsic call!");
863   CI->eraseFromParent();
864 }