1 //===-- IntrinsicLowering.cpp - Intrinsic Lowering default implementation -===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the IntrinsicLowering class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Constants.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/Module.h"
17 #include "llvm/Type.h"
18 #include "llvm/CodeGen/IntrinsicLowering.h"
19 #include "llvm/Support/IRBuilder.h"
20 #include "llvm/Target/TargetData.h"
21 #include "llvm/ADT/SmallVector.h"
24 template <class ArgIt>
25 static void EnsureFunctionExists(Module &M, const char *Name,
26 ArgIt ArgBegin, ArgIt ArgEnd,
28 // Insert a correctly-typed definition now.
29 std::vector<const Type *> ParamTys;
30 for (ArgIt I = ArgBegin; I != ArgEnd; ++I)
31 ParamTys.push_back(I->getType());
32 M.getOrInsertFunction(Name, FunctionType::get(RetTy, ParamTys, false));
35 static void EnsureFPIntrinsicsExist(Module &M, Function *Fn,
37 const char *DName, const char *LDName) {
38 // Insert definitions for all the floating point types.
39 switch((int)Fn->arg_begin()->getType()->getTypeID()) {
41 EnsureFunctionExists(M, FName, Fn->arg_begin(), Fn->arg_end(),
44 case Type::DoubleTyID:
45 EnsureFunctionExists(M, DName, Fn->arg_begin(), Fn->arg_end(),
48 case Type::X86_FP80TyID:
50 case Type::PPC_FP128TyID:
51 EnsureFunctionExists(M, LDName, Fn->arg_begin(), Fn->arg_end(),
52 Fn->arg_begin()->getType());
57 /// ReplaceCallWith - This function is used when we want to lower an intrinsic
58 /// call to a call of an external function. This handles hard cases such as
59 /// when there was already a prototype for the external function, and if that
60 /// prototype doesn't match the arguments we expect to pass in.
61 template <class ArgIt>
62 static CallInst *ReplaceCallWith(const char *NewFn, CallInst *CI,
63 ArgIt ArgBegin, ArgIt ArgEnd,
65 // If we haven't already looked up this function, check to see if the
66 // program already contains a function with this name.
67 Module *M = CI->getParent()->getParent()->getParent();
68 // Get or insert the definition now.
69 std::vector<const Type *> ParamTys;
70 for (ArgIt I = ArgBegin; I != ArgEnd; ++I)
71 ParamTys.push_back((*I)->getType());
72 Constant* FCache = M->getOrInsertFunction(NewFn,
73 FunctionType::get(RetTy, ParamTys, false));
75 IRBuilder<> Builder(CI->getParent(), CI);
76 SmallVector<Value *, 8> Args(ArgBegin, ArgEnd);
77 CallInst *NewCI = Builder.CreateCall(FCache, Args.begin(), Args.end());
78 NewCI->setName(CI->getName());
80 CI->replaceAllUsesWith(NewCI);
84 void IntrinsicLowering::AddPrototypes(Module &M) {
85 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
86 if (I->isDeclaration() && !I->use_empty())
87 switch (I->getIntrinsicID()) {
89 case Intrinsic::setjmp:
90 EnsureFunctionExists(M, "setjmp", I->arg_begin(), I->arg_end(),
93 case Intrinsic::longjmp:
94 EnsureFunctionExists(M, "longjmp", I->arg_begin(), I->arg_end(),
97 case Intrinsic::siglongjmp:
98 EnsureFunctionExists(M, "abort", I->arg_end(), I->arg_end(),
101 case Intrinsic::memcpy:
102 M.getOrInsertFunction("memcpy", PointerType::getUnqual(Type::Int8Ty),
103 PointerType::getUnqual(Type::Int8Ty),
104 PointerType::getUnqual(Type::Int8Ty),
105 TD.getIntPtrType(), (Type *)0);
107 case Intrinsic::memmove:
108 M.getOrInsertFunction("memmove", PointerType::getUnqual(Type::Int8Ty),
109 PointerType::getUnqual(Type::Int8Ty),
110 PointerType::getUnqual(Type::Int8Ty),
111 TD.getIntPtrType(), (Type *)0);
113 case Intrinsic::memset:
114 M.getOrInsertFunction("memset", PointerType::getUnqual(Type::Int8Ty),
115 PointerType::getUnqual(Type::Int8Ty),
117 TD.getIntPtrType(), (Type *)0);
119 case Intrinsic::sqrt:
120 EnsureFPIntrinsicsExist(M, I, "sqrtf", "sqrt", "sqrtl");
123 EnsureFPIntrinsicsExist(M, I, "sinf", "sin", "sinl");
126 EnsureFPIntrinsicsExist(M, I, "cosf", "cos", "cosl");
129 EnsureFPIntrinsicsExist(M, I, "powf", "pow", "powl");
132 EnsureFPIntrinsicsExist(M, I, "logf", "log", "logl");
134 case Intrinsic::log2:
135 EnsureFPIntrinsicsExist(M, I, "log2f", "log2", "log2l");
137 case Intrinsic::log10:
138 EnsureFPIntrinsicsExist(M, I, "log10f", "log10", "log10l");
141 EnsureFPIntrinsicsExist(M, I, "expf", "exp", "expl");
143 case Intrinsic::exp2:
144 EnsureFPIntrinsicsExist(M, I, "exp2f", "exp2", "exp2l");
149 /// LowerBSWAP - Emit the code to lower bswap of V before the specified
151 static Value *LowerBSWAP(Value *V, Instruction *IP) {
152 assert(V->getType()->isInteger() && "Can't bswap a non-integer type!");
154 unsigned BitSize = V->getType()->getPrimitiveSizeInBits();
156 IRBuilder<> Builder(IP->getParent(), IP);
159 default: assert(0 && "Unhandled type size of value to byteswap!");
161 Value *Tmp1 = Builder.CreateShl(V, ConstantInt::get(V->getType(), 8),
163 Value *Tmp2 = Builder.CreateLShr(V, ConstantInt::get(V->getType(), 8),
165 V = Builder.CreateOr(Tmp1, Tmp2, "bswap.i16");
169 Value *Tmp4 = Builder.CreateShl(V, ConstantInt::get(V->getType(), 24),
171 Value *Tmp3 = Builder.CreateShl(V, ConstantInt::get(V->getType(), 8),
173 Value *Tmp2 = Builder.CreateLShr(V, ConstantInt::get(V->getType(), 8),
175 Value *Tmp1 = Builder.CreateLShr(V, ConstantInt::get(V->getType(), 24),
177 Tmp3 = Builder.CreateAnd(Tmp3, ConstantInt::get(Type::Int32Ty, 0xFF0000),
179 Tmp2 = Builder.CreateAnd(Tmp2, ConstantInt::get(Type::Int32Ty, 0xFF00),
181 Tmp4 = Builder.CreateOr(Tmp4, Tmp3, "bswap.or1");
182 Tmp2 = Builder.CreateOr(Tmp2, Tmp1, "bswap.or2");
183 V = Builder.CreateOr(Tmp4, Tmp2, "bswap.i32");
187 Value *Tmp8 = Builder.CreateShl(V, ConstantInt::get(V->getType(), 56),
189 Value *Tmp7 = Builder.CreateShl(V, ConstantInt::get(V->getType(), 40),
191 Value *Tmp6 = Builder.CreateShl(V, ConstantInt::get(V->getType(), 24),
193 Value *Tmp5 = Builder.CreateShl(V, ConstantInt::get(V->getType(), 8),
195 Value* Tmp4 = Builder.CreateLShr(V, ConstantInt::get(V->getType(), 8),
197 Value* Tmp3 = Builder.CreateLShr(V, ConstantInt::get(V->getType(), 24),
199 Value* Tmp2 = Builder.CreateLShr(V, ConstantInt::get(V->getType(), 40),
201 Value* Tmp1 = Builder.CreateLShr(V, ConstantInt::get(V->getType(), 56),
203 Tmp7 = Builder.CreateAnd(Tmp7,
204 ConstantInt::get(Type::Int64Ty,
205 0xFF000000000000ULL),
207 Tmp6 = Builder.CreateAnd(Tmp6,
208 ConstantInt::get(Type::Int64Ty,
211 Tmp5 = Builder.CreateAnd(Tmp5,
212 ConstantInt::get(Type::Int64Ty, 0xFF00000000ULL),
214 Tmp4 = Builder.CreateAnd(Tmp4,
215 ConstantInt::get(Type::Int64Ty, 0xFF000000ULL),
217 Tmp3 = Builder.CreateAnd(Tmp3,
218 ConstantInt::get(Type::Int64Ty, 0xFF0000ULL),
220 Tmp2 = Builder.CreateAnd(Tmp2,
221 ConstantInt::get(Type::Int64Ty, 0xFF00ULL),
223 Tmp8 = Builder.CreateOr(Tmp8, Tmp7, "bswap.or1");
224 Tmp6 = Builder.CreateOr(Tmp6, Tmp5, "bswap.or2");
225 Tmp4 = Builder.CreateOr(Tmp4, Tmp3, "bswap.or3");
226 Tmp2 = Builder.CreateOr(Tmp2, Tmp1, "bswap.or4");
227 Tmp8 = Builder.CreateOr(Tmp8, Tmp6, "bswap.or5");
228 Tmp4 = Builder.CreateOr(Tmp4, Tmp2, "bswap.or6");
229 V = Builder.CreateOr(Tmp8, Tmp4, "bswap.i64");
236 /// LowerCTPOP - Emit the code to lower ctpop of V before the specified
238 static Value *LowerCTPOP(Value *V, Instruction *IP) {
239 assert(V->getType()->isInteger() && "Can't ctpop a non-integer type!");
241 static const uint64_t MaskValues[6] = {
242 0x5555555555555555ULL, 0x3333333333333333ULL,
243 0x0F0F0F0F0F0F0F0FULL, 0x00FF00FF00FF00FFULL,
244 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL
247 IRBuilder<> Builder(IP->getParent(), IP);
249 unsigned BitSize = V->getType()->getPrimitiveSizeInBits();
250 unsigned WordSize = (BitSize + 63) / 64;
251 Value *Count = ConstantInt::get(V->getType(), 0);
253 for (unsigned n = 0; n < WordSize; ++n) {
254 Value *PartValue = V;
255 for (unsigned i = 1, ct = 0; i < (BitSize>64 ? 64 : BitSize);
257 Value *MaskCst = ConstantInt::get(V->getType(), MaskValues[ct]);
258 Value *LHS = Builder.CreateAnd(PartValue, MaskCst, "cppop.and1");
259 Value *VShift = Builder.CreateLShr(PartValue,
260 ConstantInt::get(V->getType(), i),
262 Value *RHS = Builder.CreateAnd(VShift, MaskCst, "cppop.and2");
263 PartValue = Builder.CreateAdd(LHS, RHS, "ctpop.step");
265 Count = Builder.CreateAdd(PartValue, Count, "ctpop.part");
267 V = Builder.CreateLShr(V, ConstantInt::get(V->getType(), 64),
276 /// LowerCTLZ - Emit the code to lower ctlz of V before the specified
278 static Value *LowerCTLZ(Value *V, Instruction *IP) {
280 IRBuilder<> Builder(IP->getParent(), IP);
282 unsigned BitSize = V->getType()->getPrimitiveSizeInBits();
283 for (unsigned i = 1; i < BitSize; i <<= 1) {
284 Value *ShVal = ConstantInt::get(V->getType(), i);
285 ShVal = Builder.CreateLShr(V, ShVal, "ctlz.sh");
286 V = Builder.CreateOr(V, ShVal, "ctlz.step");
289 V = Builder.CreateNot(V);
290 return LowerCTPOP(V, IP);
293 /// Convert the llvm.part.select.iX.iY intrinsic. This intrinsic takes
294 /// three integer arguments. The first argument is the Value from which the
295 /// bits will be selected. It may be of any bit width. The second and third
296 /// arguments specify a range of bits to select with the second argument
297 /// specifying the low bit and the third argument specifying the high bit. Both
298 /// must be type i32. The result is the corresponding selected bits from the
299 /// Value in the same width as the Value (first argument). If the low bit index
300 /// is higher than the high bit index then the inverse selection is done and
301 /// the bits are returned in inverse order.
302 /// @brief Lowering of llvm.part.select intrinsic.
303 static Instruction *LowerPartSelect(CallInst *CI) {
304 IRBuilder<> Builder(*CI->getParent()->getContext());
306 // Make sure we're dealing with a part select intrinsic here
307 Function *F = CI->getCalledFunction();
308 const FunctionType *FT = F->getFunctionType();
309 if (!F->isDeclaration() || !FT->getReturnType()->isInteger() ||
310 FT->getNumParams() != 3 || !FT->getParamType(0)->isInteger() ||
311 !FT->getParamType(1)->isInteger() || !FT->getParamType(2)->isInteger())
314 // Get the intrinsic implementation function by converting all the . to _
315 // in the intrinsic's function name and then reconstructing the function
317 std::string Name(F->getName());
318 for (unsigned i = 4; i < Name.length(); ++i)
321 Module* M = F->getParent();
322 F = cast<Function>(M->getOrInsertFunction(Name, FT));
323 F->setLinkage(GlobalValue::WeakAnyLinkage);
325 // If we haven't defined the impl function yet, do so now
326 if (F->isDeclaration()) {
328 // Get the arguments to the function
329 Function::arg_iterator args = F->arg_begin();
330 Value* Val = args++; Val->setName("Val");
331 Value* Lo = args++; Lo->setName("Lo");
332 Value* Hi = args++; Hi->setName("High");
334 // We want to select a range of bits here such that [Hi, Lo] is shifted
335 // down to the low bits. However, it is quite possible that Hi is smaller
336 // than Lo in which case the bits have to be reversed.
338 // Create the blocks we will need for the two cases (forward, reverse)
339 BasicBlock* CurBB = BasicBlock::Create("entry", F);
340 BasicBlock *RevSize = BasicBlock::Create("revsize", CurBB->getParent());
341 BasicBlock *FwdSize = BasicBlock::Create("fwdsize", CurBB->getParent());
342 BasicBlock *Compute = BasicBlock::Create("compute", CurBB->getParent());
343 BasicBlock *Reverse = BasicBlock::Create("reverse", CurBB->getParent());
344 BasicBlock *RsltBlk = BasicBlock::Create("result", CurBB->getParent());
346 Builder.SetInsertPoint(CurBB);
348 // Cast Hi and Lo to the size of Val so the widths are all the same
349 if (Hi->getType() != Val->getType())
350 Hi = Builder.CreateIntCast(Hi, Val->getType(), /* isSigned */ false,
352 if (Lo->getType() != Val->getType())
353 Lo = Builder.CreateIntCast(Lo, Val->getType(), /* isSigned */ false,
356 // Compute a few things that both cases will need, up front.
357 Constant* Zero = ConstantInt::get(Val->getType(), 0);
358 Constant* One = ConstantInt::get(Val->getType(), 1);
359 Constant* AllOnes = ConstantInt::getAllOnesValue(Val->getType());
361 // Compare the Hi and Lo bit positions. This is used to determine
362 // which case we have (forward or reverse)
363 Value *Cmp = Builder.CreateICmpULT(Hi, Lo, "less");
364 Builder.CreateCondBr(Cmp, RevSize, FwdSize);
366 // First, compute the number of bits in the forward case.
367 Builder.SetInsertPoint(FwdSize);
368 Value* FBitSize = Builder.CreateSub(Hi, Lo, "fbits");
369 Builder.CreateBr(Compute);
371 // Second, compute the number of bits in the reverse case.
372 Builder.SetInsertPoint(RevSize);
373 Value* RBitSize = Builder.CreateSub(Lo, Hi, "rbits");
374 Builder.CreateBr(Compute);
376 // Now, compute the bit range. Start by getting the bitsize and the shift
377 // amount (either Hi or Lo) from PHI nodes. Then we compute a mask for
378 // the number of bits we want in the range. We shift the bits down to the
379 // least significant bits, apply the mask to zero out unwanted high bits,
380 // and we have computed the "forward" result. It may still need to be
382 Builder.SetInsertPoint(Compute);
384 // Get the BitSize from one of the two subtractions
385 PHINode *BitSize = Builder.CreatePHI(Val->getType(), "bits");
386 BitSize->reserveOperandSpace(2);
387 BitSize->addIncoming(FBitSize, FwdSize);
388 BitSize->addIncoming(RBitSize, RevSize);
390 // Get the ShiftAmount as the smaller of Hi/Lo
391 PHINode *ShiftAmt = Builder.CreatePHI(Val->getType(), "shiftamt");
392 ShiftAmt->reserveOperandSpace(2);
393 ShiftAmt->addIncoming(Lo, FwdSize);
394 ShiftAmt->addIncoming(Hi, RevSize);
396 // Increment the bit size
397 Value *BitSizePlusOne = Builder.CreateAdd(BitSize, One, "bits");
399 // Create a Mask to zero out the high order bits.
400 Value* Mask = Builder.CreateShl(AllOnes, BitSizePlusOne, "mask");
401 Mask = Builder.CreateNot(Mask, "mask");
403 // Shift the bits down and apply the mask
404 Value* FRes = Builder.CreateLShr(Val, ShiftAmt, "fres");
405 FRes = Builder.CreateAnd(FRes, Mask, "fres");
406 Builder.CreateCondBr(Cmp, Reverse, RsltBlk);
408 // In the Reverse block we have the mask already in FRes but we must reverse
409 // it by shifting FRes bits right and putting them in RRes by shifting them
411 Builder.SetInsertPoint(Reverse);
413 // First set up our loop counters
414 PHINode *Count = Builder.CreatePHI(Val->getType(), "count");
415 Count->reserveOperandSpace(2);
416 Count->addIncoming(BitSizePlusOne, Compute);
418 // Next, get the value that we are shifting.
419 PHINode *BitsToShift = Builder.CreatePHI(Val->getType(), "val");
420 BitsToShift->reserveOperandSpace(2);
421 BitsToShift->addIncoming(FRes, Compute);
423 // Finally, get the result of the last computation
424 PHINode *RRes = Builder.CreatePHI(Val->getType(), "rres");
425 RRes->reserveOperandSpace(2);
426 RRes->addIncoming(Zero, Compute);
428 // Decrement the counter
429 Value *Decr = Builder.CreateSub(Count, One, "decr");
430 Count->addIncoming(Decr, Reverse);
432 // Compute the Bit that we want to move
433 Value *Bit = Builder.CreateAnd(BitsToShift, One, "bit");
435 // Compute the new value for next iteration.
436 Value *NewVal = Builder.CreateLShr(BitsToShift, One, "rshift");
437 BitsToShift->addIncoming(NewVal, Reverse);
439 // Shift the bit into the low bits of the result.
440 Value *NewRes = Builder.CreateShl(RRes, One, "lshift");
441 NewRes = Builder.CreateOr(NewRes, Bit, "addbit");
442 RRes->addIncoming(NewRes, Reverse);
444 // Terminate loop if we've moved all the bits.
445 Value *Cond = Builder.CreateICmpEQ(Decr, Zero, "cond");
446 Builder.CreateCondBr(Cond, RsltBlk, Reverse);
448 // Finally, in the result block, select one of the two results with a PHI
449 // node and return the result;
450 Builder.SetInsertPoint(RsltBlk);
451 PHINode *BitSelect = Builder.CreatePHI(Val->getType(), "part_select");
452 BitSelect->reserveOperandSpace(2);
453 BitSelect->addIncoming(FRes, Compute);
454 BitSelect->addIncoming(NewRes, Reverse);
455 Builder.CreateRet(BitSelect);
458 // Return a call to the implementation function
459 Builder.SetInsertPoint(CI->getParent(), CI);
460 CallInst *NewCI = Builder.CreateCall3(F, CI->getOperand(1),
461 CI->getOperand(2), CI->getOperand(3));
462 NewCI->setName(CI->getName());
466 /// Convert the llvm.part.set.iX.iY.iZ intrinsic. This intrinsic takes
467 /// four integer arguments (iAny %Value, iAny %Replacement, i32 %Low, i32 %High)
468 /// The first two arguments can be any bit width. The result is the same width
469 /// as %Value. The operation replaces bits between %Low and %High with the value
470 /// in %Replacement. If %Replacement is not the same width, it is truncated or
471 /// zero extended as appropriate to fit the bits being replaced. If %Low is
472 /// greater than %High then the inverse set of bits are replaced.
473 /// @brief Lowering of llvm.bit.part.set intrinsic.
474 static Instruction *LowerPartSet(CallInst *CI) {
475 IRBuilder<> Builder(*CI->getParent()->getContext());
477 // Make sure we're dealing with a part select intrinsic here
478 Function *F = CI->getCalledFunction();
479 const FunctionType *FT = F->getFunctionType();
480 if (!F->isDeclaration() || !FT->getReturnType()->isInteger() ||
481 FT->getNumParams() != 4 || !FT->getParamType(0)->isInteger() ||
482 !FT->getParamType(1)->isInteger() || !FT->getParamType(2)->isInteger() ||
483 !FT->getParamType(3)->isInteger())
486 // Get the intrinsic implementation function by converting all the . to _
487 // in the intrinsic's function name and then reconstructing the function
489 std::string Name(F->getName());
490 for (unsigned i = 4; i < Name.length(); ++i)
493 Module* M = F->getParent();
494 F = cast<Function>(M->getOrInsertFunction(Name, FT));
495 F->setLinkage(GlobalValue::WeakAnyLinkage);
497 // If we haven't defined the impl function yet, do so now
498 if (F->isDeclaration()) {
499 // Get the arguments for the function.
500 Function::arg_iterator args = F->arg_begin();
501 Value* Val = args++; Val->setName("Val");
502 Value* Rep = args++; Rep->setName("Rep");
503 Value* Lo = args++; Lo->setName("Lo");
504 Value* Hi = args++; Hi->setName("Hi");
506 // Get some types we need
507 const IntegerType* ValTy = cast<IntegerType>(Val->getType());
508 const IntegerType* RepTy = cast<IntegerType>(Rep->getType());
509 uint32_t RepBits = RepTy->getBitWidth();
511 // Constant Definitions
512 ConstantInt* RepBitWidth = ConstantInt::get(Type::Int32Ty, RepBits);
513 ConstantInt* RepMask = ConstantInt::getAllOnesValue(RepTy);
514 ConstantInt* ValMask = ConstantInt::getAllOnesValue(ValTy);
515 ConstantInt* One = ConstantInt::get(Type::Int32Ty, 1);
516 ConstantInt* ValOne = ConstantInt::get(ValTy, 1);
517 ConstantInt* Zero = ConstantInt::get(Type::Int32Ty, 0);
518 ConstantInt* ValZero = ConstantInt::get(ValTy, 0);
520 // Basic blocks we fill in below.
521 BasicBlock* entry = BasicBlock::Create("entry", F, 0);
522 BasicBlock* large = BasicBlock::Create("large", F, 0);
523 BasicBlock* small = BasicBlock::Create("small", F, 0);
524 BasicBlock* reverse = BasicBlock::Create("reverse", F, 0);
525 BasicBlock* result = BasicBlock::Create("result", F, 0);
527 // BASIC BLOCK: entry
528 Builder.SetInsertPoint(entry);
529 // First, get the number of bits that we're placing as an i32
530 Value* is_forward = Builder.CreateICmpULT(Lo, Hi);
531 Value* Hi_pn = Builder.CreateSelect(is_forward, Hi, Lo);
532 Value* Lo_pn = Builder.CreateSelect(is_forward, Lo, Hi);
533 Value* NumBits = Builder.CreateSub(Hi_pn, Lo_pn);
534 NumBits = Builder.CreateAdd(NumBits, One);
535 // Now, convert Lo and Hi to ValTy bit width
536 Lo = Builder.CreateIntCast(Lo_pn, ValTy, /* isSigned */ false);
537 // Determine if the replacement bits are larger than the number of bits we
538 // are replacing and deal with it.
539 Value* is_large = Builder.CreateICmpULT(NumBits, RepBitWidth);
540 Builder.CreateCondBr(is_large, large, small);
542 // BASIC BLOCK: large
543 Builder.SetInsertPoint(large);
544 Value* MaskBits = Builder.CreateSub(RepBitWidth, NumBits);
545 MaskBits = Builder.CreateIntCast(MaskBits, RepMask->getType(),
546 /* isSigned */ false);
547 Value* Mask1 = Builder.CreateLShr(RepMask, MaskBits);
548 Value* Rep2 = Builder.CreateAnd(Mask1, Rep);
549 Builder.CreateBr(small);
551 // BASIC BLOCK: small
552 Builder.SetInsertPoint(small);
553 PHINode* Rep3 = Builder.CreatePHI(RepTy);
554 Rep3->reserveOperandSpace(2);
555 Rep3->addIncoming(Rep2, large);
556 Rep3->addIncoming(Rep, entry);
557 Value* Rep4 = Builder.CreateIntCast(Rep3, ValTy, /* isSigned */ false);
558 Builder.CreateCondBr(is_forward, result, reverse);
560 // BASIC BLOCK: reverse (reverses the bits of the replacement)
561 Builder.SetInsertPoint(reverse);
562 // Set up our loop counter as a PHI so we can decrement on each iteration.
563 // We will loop for the number of bits in the replacement value.
564 PHINode *Count = Builder.CreatePHI(Type::Int32Ty, "count");
565 Count->reserveOperandSpace(2);
566 Count->addIncoming(NumBits, small);
568 // Get the value that we are shifting bits out of as a PHI because
569 // we'll change this with each iteration.
570 PHINode *BitsToShift = Builder.CreatePHI(Val->getType(), "val");
571 BitsToShift->reserveOperandSpace(2);
572 BitsToShift->addIncoming(Rep4, small);
574 // Get the result of the last computation or zero on first iteration
575 PHINode *RRes = Builder.CreatePHI(Val->getType(), "rres");
576 RRes->reserveOperandSpace(2);
577 RRes->addIncoming(ValZero, small);
579 // Decrement the loop counter by one
580 Value *Decr = Builder.CreateSub(Count, One);
581 Count->addIncoming(Decr, reverse);
583 // Get the bit that we want to move into the result
584 Value *Bit = Builder.CreateAnd(BitsToShift, ValOne);
586 // Compute the new value of the bits to shift for the next iteration.
587 Value *NewVal = Builder.CreateLShr(BitsToShift, ValOne);
588 BitsToShift->addIncoming(NewVal, reverse);
590 // Shift the bit we extracted into the low bit of the result.
591 Value *NewRes = Builder.CreateShl(RRes, ValOne);
592 NewRes = Builder.CreateOr(NewRes, Bit);
593 RRes->addIncoming(NewRes, reverse);
595 // Terminate loop if we've moved all the bits.
596 Value *Cond = Builder.CreateICmpEQ(Decr, Zero);
597 Builder.CreateCondBr(Cond, result, reverse);
599 // BASIC BLOCK: result
600 Builder.SetInsertPoint(result);
601 PHINode *Rplcmnt = Builder.CreatePHI(Val->getType());
602 Rplcmnt->reserveOperandSpace(2);
603 Rplcmnt->addIncoming(NewRes, reverse);
604 Rplcmnt->addIncoming(Rep4, small);
605 Value* t0 = Builder.CreateIntCast(NumBits, ValTy, /* isSigned */ false);
606 Value* t1 = Builder.CreateShl(ValMask, Lo);
607 Value* t2 = Builder.CreateNot(t1);
608 Value* t3 = Builder.CreateShl(t1, t0);
609 Value* t4 = Builder.CreateOr(t2, t3);
610 Value* t5 = Builder.CreateAnd(t4, Val);
611 Value* t6 = Builder.CreateShl(Rplcmnt, Lo);
612 Value* Rslt = Builder.CreateOr(t5, t6, "part_set");
613 Builder.CreateRet(Rslt);
616 // Return a call to the implementation function
617 Builder.SetInsertPoint(CI->getParent(), CI);
618 CallInst *NewCI = Builder.CreateCall4(F, CI->getOperand(1),
619 CI->getOperand(2), CI->getOperand(3),
621 NewCI->setName(CI->getName());
625 static void ReplaceFPIntrinsicWithCall(CallInst *CI, const char *Fname,
627 const char *LDname) {
628 switch (CI->getOperand(1)->getType()->getTypeID()) {
629 default: assert(0 && "Invalid type in intrinsic"); abort();
630 case Type::FloatTyID:
631 ReplaceCallWith(Fname, CI, CI->op_begin() + 1, CI->op_end(),
634 case Type::DoubleTyID:
635 ReplaceCallWith(Dname, CI, CI->op_begin() + 1, CI->op_end(),
638 case Type::X86_FP80TyID:
639 case Type::FP128TyID:
640 case Type::PPC_FP128TyID:
641 ReplaceCallWith(LDname, CI, CI->op_begin() + 1, CI->op_end(),
642 CI->getOperand(1)->getType());
647 void IntrinsicLowering::LowerIntrinsicCall(CallInst *CI) {
648 IRBuilder<> Builder(CI->getParent(), CI);
650 Function *Callee = CI->getCalledFunction();
651 assert(Callee && "Cannot lower an indirect call!");
653 switch (Callee->getIntrinsicID()) {
654 case Intrinsic::not_intrinsic:
655 cerr << "Cannot lower a call to a non-intrinsic function '"
656 << Callee->getName() << "'!\n";
659 cerr << "Error: Code generator does not support intrinsic function '"
660 << Callee->getName() << "'!\n";
663 // The setjmp/longjmp intrinsics should only exist in the code if it was
664 // never optimized (ie, right out of the CFE), or if it has been hacked on
665 // by the lowerinvoke pass. In both cases, the right thing to do is to
666 // convert the call to an explicit setjmp or longjmp call.
667 case Intrinsic::setjmp: {
668 Value *V = ReplaceCallWith("setjmp", CI, CI->op_begin() + 1, CI->op_end(),
670 if (CI->getType() != Type::VoidTy)
671 CI->replaceAllUsesWith(V);
674 case Intrinsic::sigsetjmp:
675 if (CI->getType() != Type::VoidTy)
676 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
679 case Intrinsic::longjmp: {
680 ReplaceCallWith("longjmp", CI, CI->op_begin() + 1, CI->op_end(),
685 case Intrinsic::siglongjmp: {
686 // Insert the call to abort
687 ReplaceCallWith("abort", CI, CI->op_end(), CI->op_end(),
691 case Intrinsic::ctpop:
692 CI->replaceAllUsesWith(LowerCTPOP(CI->getOperand(1), CI));
695 case Intrinsic::bswap:
696 CI->replaceAllUsesWith(LowerBSWAP(CI->getOperand(1), CI));
699 case Intrinsic::ctlz:
700 CI->replaceAllUsesWith(LowerCTLZ(CI->getOperand(1), CI));
703 case Intrinsic::cttz: {
704 // cttz(x) -> ctpop(~X & (X-1))
705 Value *Src = CI->getOperand(1);
706 Value *NotSrc = Builder.CreateNot(Src);
707 NotSrc->setName(Src->getName() + ".not");
708 Value *SrcM1 = ConstantInt::get(Src->getType(), 1);
709 SrcM1 = Builder.CreateSub(Src, SrcM1);
710 Src = LowerCTPOP(Builder.CreateAnd(NotSrc, SrcM1), CI);
711 CI->replaceAllUsesWith(Src);
715 case Intrinsic::part_select:
716 CI->replaceAllUsesWith(LowerPartSelect(CI));
719 case Intrinsic::part_set:
720 CI->replaceAllUsesWith(LowerPartSet(CI));
723 case Intrinsic::stacksave:
724 case Intrinsic::stackrestore: {
726 cerr << "WARNING: this target does not support the llvm.stack"
727 << (Callee->getIntrinsicID() == Intrinsic::stacksave ?
728 "save" : "restore") << " intrinsic.\n";
730 if (Callee->getIntrinsicID() == Intrinsic::stacksave)
731 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
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())));
744 case Intrinsic::prefetch:
745 break; // Simply strip out prefetches on unsupported architectures
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));
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
763 case Intrinsic::eh_exception:
764 case Intrinsic::eh_selector_i32:
765 case Intrinsic::eh_selector_i64:
766 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
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));
775 case Intrinsic::var_annotation:
776 break; // Strip out annotate intrinsic
778 case Intrinsic::memcpy: {
779 const IntegerType *IntPtr = TD.getIntPtrType();
780 Value *Size = Builder.CreateIntCast(CI->getOperand(3), IntPtr,
781 /* isSigned */ false);
783 Ops[0] = CI->getOperand(1);
784 Ops[1] = CI->getOperand(2);
786 ReplaceCallWith("memcpy", CI, Ops, Ops+3, CI->getOperand(1)->getType());
789 case Intrinsic::memmove: {
790 const IntegerType *IntPtr = TD.getIntPtrType();
791 Value *Size = Builder.CreateIntCast(CI->getOperand(3), IntPtr,
792 /* isSigned */ false);
794 Ops[0] = CI->getOperand(1);
795 Ops[1] = CI->getOperand(2);
797 ReplaceCallWith("memmove", CI, Ops, Ops+3, CI->getOperand(1)->getType());
800 case Intrinsic::memset: {
801 const IntegerType *IntPtr = TD.getIntPtrType();
802 Value *Size = Builder.CreateIntCast(CI->getOperand(3), IntPtr,
803 /* isSigned */ false);
805 Ops[0] = CI->getOperand(1);
806 // Extend the amount to i32.
807 Ops[1] = Builder.CreateIntCast(CI->getOperand(2), Type::Int32Ty,
808 /* isSigned */ false);
810 ReplaceCallWith("memset", CI, Ops, Ops+3, CI->getOperand(1)->getType());
813 case Intrinsic::sqrt: {
814 ReplaceFPIntrinsicWithCall(CI, "sqrtf", "sqrt", "sqrtl");
817 case Intrinsic::log: {
818 ReplaceFPIntrinsicWithCall(CI, "logf", "log", "logl");
821 case Intrinsic::log2: {
822 ReplaceFPIntrinsicWithCall(CI, "log2f", "log2", "log2l");
825 case Intrinsic::log10: {
826 ReplaceFPIntrinsicWithCall(CI, "log10f", "log10", "log10l");
829 case Intrinsic::exp: {
830 ReplaceFPIntrinsicWithCall(CI, "expf", "exp", "expl");
833 case Intrinsic::exp2: {
834 ReplaceFPIntrinsicWithCall(CI, "exp2f", "exp2", "exp2l");
837 case Intrinsic::pow: {
838 ReplaceFPIntrinsicWithCall(CI, "powf", "pow", "powl");
841 case Intrinsic::flt_rounds:
842 // Lower to "round to the nearest"
843 if (CI->getType() != Type::VoidTy)
844 CI->replaceAllUsesWith(ConstantInt::get(CI->getType(), 1));
848 assert(CI->use_empty() &&
849 "Lowering should have eliminated any uses of the intrinsic call!");
850 CI->eraseFromParent();