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
,
64 const Type
*RetTy
, Constant
*&FCache
) {
66 // If we haven't already looked up this function, check to see if the
67 // program already contains a function with this name.
68 Module
*M
= CI
->getParent()->getParent()->getParent();
69 // Get or insert the definition now.
70 std::vector
<const Type
*> ParamTys
;
71 for (ArgIt I
= ArgBegin
; I
!= ArgEnd
; ++I
)
72 ParamTys
.push_back((*I
)->getType());
73 FCache
= M
->getOrInsertFunction(NewFn
,
74 FunctionType::get(RetTy
, ParamTys
, false));
77 IRBuilder
<> Builder(CI
->getParent(), CI
);
78 SmallVector
<Value
*, 8> Args(ArgBegin
, ArgEnd
);
79 CallInst
*NewCI
= Builder
.CreateCall(FCache
, Args
.begin(), Args
.end());
80 NewCI
->setName(CI
->getName());
82 CI
->replaceAllUsesWith(NewCI
);
86 void IntrinsicLowering::AddPrototypes(Module
&M
) {
87 for (Module::iterator I
= M
.begin(), E
= M
.end(); I
!= E
; ++I
)
88 if (I
->isDeclaration() && !I
->use_empty())
89 switch (I
->getIntrinsicID()) {
91 case Intrinsic::setjmp
:
92 EnsureFunctionExists(M
, "setjmp", I
->arg_begin(), I
->arg_end(),
95 case Intrinsic::longjmp
:
96 EnsureFunctionExists(M
, "longjmp", I
->arg_begin(), I
->arg_end(),
99 case Intrinsic::siglongjmp
:
100 EnsureFunctionExists(M
, "abort", I
->arg_end(), I
->arg_end(),
103 case Intrinsic::memcpy
:
104 M
.getOrInsertFunction("memcpy", PointerType::getUnqual(Type::Int8Ty
),
105 PointerType::getUnqual(Type::Int8Ty
),
106 PointerType::getUnqual(Type::Int8Ty
),
107 TD
.getIntPtrType(), (Type
*)0);
109 case Intrinsic::memmove
:
110 M
.getOrInsertFunction("memmove", PointerType::getUnqual(Type::Int8Ty
),
111 PointerType::getUnqual(Type::Int8Ty
),
112 PointerType::getUnqual(Type::Int8Ty
),
113 TD
.getIntPtrType(), (Type
*)0);
115 case Intrinsic::memset
:
116 M
.getOrInsertFunction("memset", PointerType::getUnqual(Type::Int8Ty
),
117 PointerType::getUnqual(Type::Int8Ty
),
119 TD
.getIntPtrType(), (Type
*)0);
121 case Intrinsic::sqrt
:
122 EnsureFPIntrinsicsExist(M
, I
, "sqrtf", "sqrt", "sqrtl");
125 EnsureFPIntrinsicsExist(M
, I
, "sinf", "sin", "sinl");
128 EnsureFPIntrinsicsExist(M
, I
, "cosf", "cos", "cosl");
131 EnsureFPIntrinsicsExist(M
, I
, "powf", "pow", "powl");
134 EnsureFPIntrinsicsExist(M
, I
, "logf", "log", "logl");
136 case Intrinsic::log2
:
137 EnsureFPIntrinsicsExist(M
, I
, "log2f", "log2", "log2l");
139 case Intrinsic::log10
:
140 EnsureFPIntrinsicsExist(M
, I
, "log10f", "log10", "log10l");
143 EnsureFPIntrinsicsExist(M
, I
, "expf", "exp", "expl");
145 case Intrinsic::exp2
:
146 EnsureFPIntrinsicsExist(M
, I
, "exp2f", "exp2", "exp2l");
151 /// LowerBSWAP - Emit the code to lower bswap of V before the specified
153 static Value
*LowerBSWAP(Value
*V
, Instruction
*IP
) {
154 assert(V
->getType()->isInteger() && "Can't bswap a non-integer type!");
156 unsigned BitSize
= V
->getType()->getPrimitiveSizeInBits();
158 IRBuilder
<> Builder(IP
->getParent(), IP
);
161 default: assert(0 && "Unhandled type size of value to byteswap!");
163 Value
*Tmp1
= Builder
.CreateShl(V
, ConstantInt::get(V
->getType(), 8),
165 Value
*Tmp2
= Builder
.CreateLShr(V
, ConstantInt::get(V
->getType(), 8),
167 V
= Builder
.CreateOr(Tmp1
, Tmp2
, "bswap.i16");
171 Value
*Tmp4
= Builder
.CreateShl(V
, ConstantInt::get(V
->getType(), 24),
173 Value
*Tmp3
= Builder
.CreateShl(V
, ConstantInt::get(V
->getType(), 8),
175 Value
*Tmp2
= Builder
.CreateLShr(V
, ConstantInt::get(V
->getType(), 8),
177 Value
*Tmp1
= Builder
.CreateLShr(V
, ConstantInt::get(V
->getType(), 24),
179 Tmp3
= Builder
.CreateAnd(Tmp3
, ConstantInt::get(Type::Int32Ty
, 0xFF0000),
181 Tmp2
= Builder
.CreateAnd(Tmp2
, ConstantInt::get(Type::Int32Ty
, 0xFF00),
183 Tmp4
= Builder
.CreateOr(Tmp4
, Tmp3
, "bswap.or1");
184 Tmp2
= Builder
.CreateOr(Tmp2
, Tmp1
, "bswap.or2");
185 V
= Builder
.CreateOr(Tmp4
, Tmp2
, "bswap.i32");
189 Value
*Tmp8
= Builder
.CreateShl(V
, ConstantInt::get(V
->getType(), 56),
191 Value
*Tmp7
= Builder
.CreateShl(V
, ConstantInt::get(V
->getType(), 40),
193 Value
*Tmp6
= Builder
.CreateShl(V
, ConstantInt::get(V
->getType(), 24),
195 Value
*Tmp5
= Builder
.CreateShl(V
, ConstantInt::get(V
->getType(), 8),
197 Value
* Tmp4
= Builder
.CreateLShr(V
, ConstantInt::get(V
->getType(), 8),
199 Value
* Tmp3
= Builder
.CreateLShr(V
, ConstantInt::get(V
->getType(), 24),
201 Value
* Tmp2
= Builder
.CreateLShr(V
, ConstantInt::get(V
->getType(), 40),
203 Value
* Tmp1
= Builder
.CreateLShr(V
, ConstantInt::get(V
->getType(), 56),
205 Tmp7
= Builder
.CreateAnd(Tmp7
,
206 ConstantInt::get(Type::Int64Ty
,
207 0xFF000000000000ULL
),
209 Tmp6
= Builder
.CreateAnd(Tmp6
,
210 ConstantInt::get(Type::Int64Ty
,
213 Tmp5
= Builder
.CreateAnd(Tmp5
,
214 ConstantInt::get(Type::Int64Ty
, 0xFF00000000ULL
),
216 Tmp4
= Builder
.CreateAnd(Tmp4
,
217 ConstantInt::get(Type::Int64Ty
, 0xFF000000ULL
),
219 Tmp3
= Builder
.CreateAnd(Tmp3
,
220 ConstantInt::get(Type::Int64Ty
, 0xFF0000ULL
),
222 Tmp2
= Builder
.CreateAnd(Tmp2
,
223 ConstantInt::get(Type::Int64Ty
, 0xFF00ULL
),
225 Tmp8
= Builder
.CreateOr(Tmp8
, Tmp7
, "bswap.or1");
226 Tmp6
= Builder
.CreateOr(Tmp6
, Tmp5
, "bswap.or2");
227 Tmp4
= Builder
.CreateOr(Tmp4
, Tmp3
, "bswap.or3");
228 Tmp2
= Builder
.CreateOr(Tmp2
, Tmp1
, "bswap.or4");
229 Tmp8
= Builder
.CreateOr(Tmp8
, Tmp6
, "bswap.or5");
230 Tmp4
= Builder
.CreateOr(Tmp4
, Tmp2
, "bswap.or6");
231 V
= Builder
.CreateOr(Tmp8
, Tmp4
, "bswap.i64");
238 /// LowerCTPOP - Emit the code to lower ctpop of V before the specified
240 static Value
*LowerCTPOP(Value
*V
, Instruction
*IP
) {
241 assert(V
->getType()->isInteger() && "Can't ctpop a non-integer type!");
243 static const uint64_t MaskValues
[6] = {
244 0x5555555555555555ULL
, 0x3333333333333333ULL
,
245 0x0F0F0F0F0F0F0F0FULL
, 0x00FF00FF00FF00FFULL
,
246 0x0000FFFF0000FFFFULL
, 0x00000000FFFFFFFFULL
249 IRBuilder
<> Builder(IP
->getParent(), IP
);
251 unsigned BitSize
= V
->getType()->getPrimitiveSizeInBits();
252 unsigned WordSize
= (BitSize
+ 63) / 64;
253 Value
*Count
= ConstantInt::get(V
->getType(), 0);
255 for (unsigned n
= 0; n
< WordSize
; ++n
) {
256 Value
*PartValue
= V
;
257 for (unsigned i
= 1, ct
= 0; i
< (BitSize
>64 ? 64 : BitSize
);
259 Value
*MaskCst
= ConstantInt::get(V
->getType(), MaskValues
[ct
]);
260 Value
*LHS
= Builder
.CreateAnd(PartValue
, MaskCst
, "cppop.and1");
261 Value
*VShift
= Builder
.CreateLShr(PartValue
,
262 ConstantInt::get(V
->getType(), i
),
264 Value
*RHS
= Builder
.CreateAnd(VShift
, MaskCst
, "cppop.and2");
265 PartValue
= Builder
.CreateAdd(LHS
, RHS
, "ctpop.step");
267 Count
= Builder
.CreateAdd(PartValue
, Count
, "ctpop.part");
269 V
= Builder
.CreateLShr(V
, ConstantInt::get(V
->getType(), 64),
278 /// LowerCTLZ - Emit the code to lower ctlz of V before the specified
280 static Value
*LowerCTLZ(Value
*V
, Instruction
*IP
) {
282 IRBuilder
<> Builder(IP
->getParent(), IP
);
284 unsigned BitSize
= V
->getType()->getPrimitiveSizeInBits();
285 for (unsigned i
= 1; i
< BitSize
; i
<<= 1) {
286 Value
*ShVal
= ConstantInt::get(V
->getType(), i
);
287 ShVal
= Builder
.CreateLShr(V
, ShVal
, "ctlz.sh");
288 V
= Builder
.CreateOr(V
, ShVal
, "ctlz.step");
291 V
= Builder
.CreateNot(V
);
292 return LowerCTPOP(V
, IP
);
295 /// Convert the llvm.part.select.iX.iY intrinsic. This intrinsic takes
296 /// three integer arguments. The first argument is the Value from which the
297 /// bits will be selected. It may be of any bit width. The second and third
298 /// arguments specify a range of bits to select with the second argument
299 /// specifying the low bit and the third argument specifying the high bit. Both
300 /// must be type i32. The result is the corresponding selected bits from the
301 /// Value in the same width as the Value (first argument). If the low bit index
302 /// is higher than the high bit index then the inverse selection is done and
303 /// the bits are returned in inverse order.
304 /// @brief Lowering of llvm.part.select intrinsic.
305 static Instruction
*LowerPartSelect(CallInst
*CI
) {
308 // Make sure we're dealing with a part select intrinsic here
309 Function
*F
= CI
->getCalledFunction();
310 const FunctionType
*FT
= F
->getFunctionType();
311 if (!F
->isDeclaration() || !FT
->getReturnType()->isInteger() ||
312 FT
->getNumParams() != 3 || !FT
->getParamType(0)->isInteger() ||
313 !FT
->getParamType(1)->isInteger() || !FT
->getParamType(2)->isInteger())
316 // Get the intrinsic implementation function by converting all the . to _
317 // in the intrinsic's function name and then reconstructing the function
319 std::string
Name(F
->getName());
320 for (unsigned i
= 4; i
< Name
.length(); ++i
)
323 Module
* M
= F
->getParent();
324 F
= cast
<Function
>(M
->getOrInsertFunction(Name
, FT
));
325 F
->setLinkage(GlobalValue::WeakAnyLinkage
);
327 // If we haven't defined the impl function yet, do so now
328 if (F
->isDeclaration()) {
330 // Get the arguments to the function
331 Function::arg_iterator args
= F
->arg_begin();
332 Value
* Val
= args
++; Val
->setName("Val");
333 Value
* Lo
= args
++; Lo
->setName("Lo");
334 Value
* Hi
= args
++; Hi
->setName("High");
336 // We want to select a range of bits here such that [Hi, Lo] is shifted
337 // down to the low bits. However, it is quite possible that Hi is smaller
338 // than Lo in which case the bits have to be reversed.
340 // Create the blocks we will need for the two cases (forward, reverse)
341 BasicBlock
* CurBB
= BasicBlock::Create("entry", F
);
342 BasicBlock
*RevSize
= BasicBlock::Create("revsize", CurBB
->getParent());
343 BasicBlock
*FwdSize
= BasicBlock::Create("fwdsize", CurBB
->getParent());
344 BasicBlock
*Compute
= BasicBlock::Create("compute", CurBB
->getParent());
345 BasicBlock
*Reverse
= BasicBlock::Create("reverse", CurBB
->getParent());
346 BasicBlock
*RsltBlk
= BasicBlock::Create("result", CurBB
->getParent());
348 Builder
.SetInsertPoint(CurBB
);
350 // Cast Hi and Lo to the size of Val so the widths are all the same
351 if (Hi
->getType() != Val
->getType())
352 Hi
= Builder
.CreateIntCast(Hi
, Val
->getType(), /* isSigned */ false,
354 if (Lo
->getType() != Val
->getType())
355 Lo
= Builder
.CreateIntCast(Lo
, Val
->getType(), /* isSigned */ false,
358 // Compute a few things that both cases will need, up front.
359 Constant
* Zero
= ConstantInt::get(Val
->getType(), 0);
360 Constant
* One
= ConstantInt::get(Val
->getType(), 1);
361 Constant
* AllOnes
= ConstantInt::getAllOnesValue(Val
->getType());
363 // Compare the Hi and Lo bit positions. This is used to determine
364 // which case we have (forward or reverse)
365 Value
*Cmp
= Builder
.CreateICmpULT(Hi
, Lo
, "less");
366 Builder
.CreateCondBr(Cmp
, RevSize
, FwdSize
);
368 // First, compute the number of bits in the forward case.
369 Builder
.SetInsertPoint(FwdSize
);
370 Value
* FBitSize
= Builder
.CreateSub(Hi
, Lo
, "fbits");
371 Builder
.CreateBr(Compute
);
373 // Second, compute the number of bits in the reverse case.
374 Builder
.SetInsertPoint(RevSize
);
375 Value
* RBitSize
= Builder
.CreateSub(Lo
, Hi
, "rbits");
376 Builder
.CreateBr(Compute
);
378 // Now, compute the bit range. Start by getting the bitsize and the shift
379 // amount (either Hi or Lo) from PHI nodes. Then we compute a mask for
380 // the number of bits we want in the range. We shift the bits down to the
381 // least significant bits, apply the mask to zero out unwanted high bits,
382 // and we have computed the "forward" result. It may still need to be
384 Builder
.SetInsertPoint(Compute
);
386 // Get the BitSize from one of the two subtractions
387 PHINode
*BitSize
= Builder
.CreatePHI(Val
->getType(), "bits");
388 BitSize
->reserveOperandSpace(2);
389 BitSize
->addIncoming(FBitSize
, FwdSize
);
390 BitSize
->addIncoming(RBitSize
, RevSize
);
392 // Get the ShiftAmount as the smaller of Hi/Lo
393 PHINode
*ShiftAmt
= Builder
.CreatePHI(Val
->getType(), "shiftamt");
394 ShiftAmt
->reserveOperandSpace(2);
395 ShiftAmt
->addIncoming(Lo
, FwdSize
);
396 ShiftAmt
->addIncoming(Hi
, RevSize
);
398 // Increment the bit size
399 Value
*BitSizePlusOne
= Builder
.CreateAdd(BitSize
, One
, "bits");
401 // Create a Mask to zero out the high order bits.
402 Value
* Mask
= Builder
.CreateShl(AllOnes
, BitSizePlusOne
, "mask");
403 Mask
= Builder
.CreateNot(Mask
, "mask");
405 // Shift the bits down and apply the mask
406 Value
* FRes
= Builder
.CreateLShr(Val
, ShiftAmt
, "fres");
407 FRes
= Builder
.CreateAnd(FRes
, Mask
, "fres");
408 Builder
.CreateCondBr(Cmp
, Reverse
, RsltBlk
);
410 // In the Reverse block we have the mask already in FRes but we must reverse
411 // it by shifting FRes bits right and putting them in RRes by shifting them
413 Builder
.SetInsertPoint(Reverse
);
415 // First set up our loop counters
416 PHINode
*Count
= Builder
.CreatePHI(Val
->getType(), "count");
417 Count
->reserveOperandSpace(2);
418 Count
->addIncoming(BitSizePlusOne
, Compute
);
420 // Next, get the value that we are shifting.
421 PHINode
*BitsToShift
= Builder
.CreatePHI(Val
->getType(), "val");
422 BitsToShift
->reserveOperandSpace(2);
423 BitsToShift
->addIncoming(FRes
, Compute
);
425 // Finally, get the result of the last computation
426 PHINode
*RRes
= Builder
.CreatePHI(Val
->getType(), "rres");
427 RRes
->reserveOperandSpace(2);
428 RRes
->addIncoming(Zero
, Compute
);
430 // Decrement the counter
431 Value
*Decr
= Builder
.CreateSub(Count
, One
, "decr");
432 Count
->addIncoming(Decr
, Reverse
);
434 // Compute the Bit that we want to move
435 Value
*Bit
= Builder
.CreateAnd(BitsToShift
, One
, "bit");
437 // Compute the new value for next iteration.
438 Value
*NewVal
= Builder
.CreateLShr(BitsToShift
, One
, "rshift");
439 BitsToShift
->addIncoming(NewVal
, Reverse
);
441 // Shift the bit into the low bits of the result.
442 Value
*NewRes
= Builder
.CreateShl(RRes
, One
, "lshift");
443 NewRes
= Builder
.CreateOr(NewRes
, Bit
, "addbit");
444 RRes
->addIncoming(NewRes
, Reverse
);
446 // Terminate loop if we've moved all the bits.
447 Value
*Cond
= Builder
.CreateICmpEQ(Decr
, Zero
, "cond");
448 Builder
.CreateCondBr(Cond
, RsltBlk
, Reverse
);
450 // Finally, in the result block, select one of the two results with a PHI
451 // node and return the result;
452 Builder
.SetInsertPoint(RsltBlk
);
453 PHINode
*BitSelect
= Builder
.CreatePHI(Val
->getType(), "part_select");
454 BitSelect
->reserveOperandSpace(2);
455 BitSelect
->addIncoming(FRes
, Compute
);
456 BitSelect
->addIncoming(NewRes
, Reverse
);
457 Builder
.CreateRet(BitSelect
);
460 // Return a call to the implementation function
461 Builder
.SetInsertPoint(CI
->getParent(), CI
);
462 CallInst
*NewCI
= Builder
.CreateCall3(F
, CI
->getOperand(1),
463 CI
->getOperand(2), CI
->getOperand(3));
464 NewCI
->setName(CI
->getName());
468 /// Convert the llvm.part.set.iX.iY.iZ intrinsic. This intrinsic takes
469 /// four integer arguments (iAny %Value, iAny %Replacement, i32 %Low, i32 %High)
470 /// The first two arguments can be any bit width. The result is the same width
471 /// as %Value. The operation replaces bits between %Low and %High with the value
472 /// in %Replacement. If %Replacement is not the same width, it is truncated or
473 /// zero extended as appropriate to fit the bits being replaced. If %Low is
474 /// greater than %High then the inverse set of bits are replaced.
475 /// @brief Lowering of llvm.bit.part.set intrinsic.
476 static Instruction
*LowerPartSet(CallInst
*CI
) {
479 // Make sure we're dealing with a part select intrinsic here
480 Function
*F
= CI
->getCalledFunction();
481 const FunctionType
*FT
= F
->getFunctionType();
482 if (!F
->isDeclaration() || !FT
->getReturnType()->isInteger() ||
483 FT
->getNumParams() != 4 || !FT
->getParamType(0)->isInteger() ||
484 !FT
->getParamType(1)->isInteger() || !FT
->getParamType(2)->isInteger() ||
485 !FT
->getParamType(3)->isInteger())
488 // Get the intrinsic implementation function by converting all the . to _
489 // in the intrinsic's function name and then reconstructing the function
491 std::string
Name(F
->getName());
492 for (unsigned i
= 4; i
< Name
.length(); ++i
)
495 Module
* M
= F
->getParent();
496 F
= cast
<Function
>(M
->getOrInsertFunction(Name
, FT
));
497 F
->setLinkage(GlobalValue::WeakAnyLinkage
);
499 // If we haven't defined the impl function yet, do so now
500 if (F
->isDeclaration()) {
501 // Get the arguments for the function.
502 Function::arg_iterator args
= F
->arg_begin();
503 Value
* Val
= args
++; Val
->setName("Val");
504 Value
* Rep
= args
++; Rep
->setName("Rep");
505 Value
* Lo
= args
++; Lo
->setName("Lo");
506 Value
* Hi
= args
++; Hi
->setName("Hi");
508 // Get some types we need
509 const IntegerType
* ValTy
= cast
<IntegerType
>(Val
->getType());
510 const IntegerType
* RepTy
= cast
<IntegerType
>(Rep
->getType());
511 uint32_t RepBits
= RepTy
->getBitWidth();
513 // Constant Definitions
514 ConstantInt
* RepBitWidth
= ConstantInt::get(Type::Int32Ty
, RepBits
);
515 ConstantInt
* RepMask
= ConstantInt::getAllOnesValue(RepTy
);
516 ConstantInt
* ValMask
= ConstantInt::getAllOnesValue(ValTy
);
517 ConstantInt
* One
= ConstantInt::get(Type::Int32Ty
, 1);
518 ConstantInt
* ValOne
= ConstantInt::get(ValTy
, 1);
519 ConstantInt
* Zero
= ConstantInt::get(Type::Int32Ty
, 0);
520 ConstantInt
* ValZero
= ConstantInt::get(ValTy
, 0);
522 // Basic blocks we fill in below.
523 BasicBlock
* entry
= BasicBlock::Create("entry", F
, 0);
524 BasicBlock
* large
= BasicBlock::Create("large", F
, 0);
525 BasicBlock
* small
= BasicBlock::Create("small", F
, 0);
526 BasicBlock
* reverse
= BasicBlock::Create("reverse", F
, 0);
527 BasicBlock
* result
= BasicBlock::Create("result", F
, 0);
529 // BASIC BLOCK: entry
530 Builder
.SetInsertPoint(entry
);
531 // First, get the number of bits that we're placing as an i32
532 Value
* is_forward
= Builder
.CreateICmpULT(Lo
, Hi
);
533 Value
* Hi_pn
= Builder
.CreateSelect(is_forward
, Hi
, Lo
);
534 Value
* Lo_pn
= Builder
.CreateSelect(is_forward
, Lo
, Hi
);
535 Value
* NumBits
= Builder
.CreateSub(Hi_pn
, Lo_pn
);
536 NumBits
= Builder
.CreateAdd(NumBits
, One
);
537 // Now, convert Lo and Hi to ValTy bit width
538 Lo
= Builder
.CreateIntCast(Lo_pn
, ValTy
, /* isSigned */ false);
539 // Determine if the replacement bits are larger than the number of bits we
540 // are replacing and deal with it.
541 Value
* is_large
= Builder
.CreateICmpULT(NumBits
, RepBitWidth
);
542 Builder
.CreateCondBr(is_large
, large
, small
);
544 // BASIC BLOCK: large
545 Builder
.SetInsertPoint(large
);
546 Value
* MaskBits
= Builder
.CreateSub(RepBitWidth
, NumBits
);
547 MaskBits
= Builder
.CreateIntCast(MaskBits
, RepMask
->getType(),
548 /* isSigned */ false);
549 Value
* Mask1
= Builder
.CreateLShr(RepMask
, MaskBits
);
550 Value
* Rep2
= Builder
.CreateAnd(Mask1
, Rep
);
551 Builder
.CreateBr(small
);
553 // BASIC BLOCK: small
554 Builder
.SetInsertPoint(small
);
555 PHINode
* Rep3
= Builder
.CreatePHI(RepTy
);
556 Rep3
->reserveOperandSpace(2);
557 Rep3
->addIncoming(Rep2
, large
);
558 Rep3
->addIncoming(Rep
, entry
);
559 Value
* Rep4
= Builder
.CreateIntCast(Rep3
, ValTy
, /* isSigned */ false);
560 Builder
.CreateCondBr(is_forward
, result
, reverse
);
562 // BASIC BLOCK: reverse (reverses the bits of the replacement)
563 Builder
.SetInsertPoint(reverse
);
564 // Set up our loop counter as a PHI so we can decrement on each iteration.
565 // We will loop for the number of bits in the replacement value.
566 PHINode
*Count
= Builder
.CreatePHI(Type::Int32Ty
, "count");
567 Count
->reserveOperandSpace(2);
568 Count
->addIncoming(NumBits
, small
);
570 // Get the value that we are shifting bits out of as a PHI because
571 // we'll change this with each iteration.
572 PHINode
*BitsToShift
= Builder
.CreatePHI(Val
->getType(), "val");
573 BitsToShift
->reserveOperandSpace(2);
574 BitsToShift
->addIncoming(Rep4
, small
);
576 // Get the result of the last computation or zero on first iteration
577 PHINode
*RRes
= Builder
.CreatePHI(Val
->getType(), "rres");
578 RRes
->reserveOperandSpace(2);
579 RRes
->addIncoming(ValZero
, small
);
581 // Decrement the loop counter by one
582 Value
*Decr
= Builder
.CreateSub(Count
, One
);
583 Count
->addIncoming(Decr
, reverse
);
585 // Get the bit that we want to move into the result
586 Value
*Bit
= Builder
.CreateAnd(BitsToShift
, ValOne
);
588 // Compute the new value of the bits to shift for the next iteration.
589 Value
*NewVal
= Builder
.CreateLShr(BitsToShift
, ValOne
);
590 BitsToShift
->addIncoming(NewVal
, reverse
);
592 // Shift the bit we extracted into the low bit of the result.
593 Value
*NewRes
= Builder
.CreateShl(RRes
, ValOne
);
594 NewRes
= Builder
.CreateOr(NewRes
, Bit
);
595 RRes
->addIncoming(NewRes
, reverse
);
597 // Terminate loop if we've moved all the bits.
598 Value
*Cond
= Builder
.CreateICmpEQ(Decr
, Zero
);
599 Builder
.CreateCondBr(Cond
, result
, reverse
);
601 // BASIC BLOCK: result
602 Builder
.SetInsertPoint(result
);
603 PHINode
*Rplcmnt
= Builder
.CreatePHI(Val
->getType());
604 Rplcmnt
->reserveOperandSpace(2);
605 Rplcmnt
->addIncoming(NewRes
, reverse
);
606 Rplcmnt
->addIncoming(Rep4
, small
);
607 Value
* t0
= Builder
.CreateIntCast(NumBits
, ValTy
, /* isSigned */ false);
608 Value
* t1
= Builder
.CreateShl(ValMask
, Lo
);
609 Value
* t2
= Builder
.CreateNot(t1
);
610 Value
* t3
= Builder
.CreateShl(t1
, t0
);
611 Value
* t4
= Builder
.CreateOr(t2
, t3
);
612 Value
* t5
= Builder
.CreateAnd(t4
, Val
);
613 Value
* t6
= Builder
.CreateShl(Rplcmnt
, Lo
);
614 Value
* Rslt
= Builder
.CreateOr(t5
, t6
, "part_set");
615 Builder
.CreateRet(Rslt
);
618 // Return a call to the implementation function
619 Builder
.SetInsertPoint(CI
->getParent(), CI
);
620 CallInst
*NewCI
= Builder
.CreateCall4(F
, CI
->getOperand(1),
621 CI
->getOperand(2), CI
->getOperand(3),
623 NewCI
->setName(CI
->getName());
627 static void ReplaceFPIntrinsicWithCall(CallInst
*CI
, Constant
*FCache
,
628 Constant
*DCache
, Constant
*LDCache
,
629 const char *Fname
, const char *Dname
,
630 const char *LDname
) {
631 switch (CI
->getOperand(1)->getType()->getTypeID()) {
632 default: assert(0 && "Invalid type in intrinsic"); abort();
633 case Type::FloatTyID
:
634 ReplaceCallWith(Fname
, CI
, CI
->op_begin() + 1, CI
->op_end(),
635 Type::FloatTy
, FCache
);
637 case Type::DoubleTyID
:
638 ReplaceCallWith(Dname
, CI
, CI
->op_begin() + 1, CI
->op_end(),
639 Type::DoubleTy
, DCache
);
641 case Type::X86_FP80TyID
:
642 case Type::FP128TyID
:
643 case Type::PPC_FP128TyID
:
644 ReplaceCallWith(LDname
, CI
, CI
->op_begin() + 1, CI
->op_end(),
645 CI
->getOperand(1)->getType(), LDCache
);
650 void IntrinsicLowering::LowerIntrinsicCall(CallInst
*CI
) {
651 IRBuilder
<> Builder(CI
->getParent(), CI
);
653 Function
*Callee
= CI
->getCalledFunction();
654 assert(Callee
&& "Cannot lower an indirect call!");
656 switch (Callee
->getIntrinsicID()) {
657 case Intrinsic::not_intrinsic
:
658 cerr
<< "Cannot lower a call to a non-intrinsic function '"
659 << Callee
->getName() << "'!\n";
662 cerr
<< "Error: Code generator does not support intrinsic function '"
663 << Callee
->getName() << "'!\n";
666 // The setjmp/longjmp intrinsics should only exist in the code if it was
667 // never optimized (ie, right out of the CFE), or if it has been hacked on
668 // by the lowerinvoke pass. In both cases, the right thing to do is to
669 // convert the call to an explicit setjmp or longjmp call.
670 case Intrinsic::setjmp
: {
671 static Constant
*SetjmpFCache
= 0;
672 Value
*V
= ReplaceCallWith("setjmp", CI
, CI
->op_begin() + 1, CI
->op_end(),
673 Type::Int32Ty
, SetjmpFCache
);
674 if (CI
->getType() != Type::VoidTy
)
675 CI
->replaceAllUsesWith(V
);
678 case Intrinsic::sigsetjmp
:
679 if (CI
->getType() != Type::VoidTy
)
680 CI
->replaceAllUsesWith(Constant::getNullValue(CI
->getType()));
683 case Intrinsic::longjmp
: {
684 static Constant
*LongjmpFCache
= 0;
685 ReplaceCallWith("longjmp", CI
, CI
->op_begin() + 1, CI
->op_end(),
686 Type::VoidTy
, LongjmpFCache
);
690 case Intrinsic::siglongjmp
: {
691 // Insert the call to abort
692 static Constant
*AbortFCache
= 0;
693 ReplaceCallWith("abort", CI
, CI
->op_end(), CI
->op_end(),
694 Type::VoidTy
, AbortFCache
);
697 case Intrinsic::ctpop
:
698 CI
->replaceAllUsesWith(LowerCTPOP(CI
->getOperand(1), CI
));
701 case Intrinsic::bswap
:
702 CI
->replaceAllUsesWith(LowerBSWAP(CI
->getOperand(1), CI
));
705 case Intrinsic::ctlz
:
706 CI
->replaceAllUsesWith(LowerCTLZ(CI
->getOperand(1), CI
));
709 case Intrinsic::cttz
: {
710 // cttz(x) -> ctpop(~X & (X-1))
711 Value
*Src
= CI
->getOperand(1);
712 Value
*NotSrc
= Builder
.CreateNot(Src
);
713 NotSrc
->setName(Src
->getName() + ".not");
714 Value
*SrcM1
= ConstantInt::get(Src
->getType(), 1);
715 SrcM1
= Builder
.CreateSub(Src
, SrcM1
);
716 Src
= LowerCTPOP(Builder
.CreateAnd(NotSrc
, SrcM1
), CI
);
717 CI
->replaceAllUsesWith(Src
);
721 case Intrinsic::part_select
:
722 CI
->replaceAllUsesWith(LowerPartSelect(CI
));
725 case Intrinsic::part_set
:
726 CI
->replaceAllUsesWith(LowerPartSet(CI
));
729 case Intrinsic::stacksave
:
730 case Intrinsic::stackrestore
: {
731 static bool Warned
= false;
733 cerr
<< "WARNING: this target does not support the llvm.stack"
734 << (Callee
->getIntrinsicID() == Intrinsic::stacksave
?
735 "save" : "restore") << " intrinsic.\n";
737 if (Callee
->getIntrinsicID() == Intrinsic::stacksave
)
738 CI
->replaceAllUsesWith(Constant::getNullValue(CI
->getType()));
742 case Intrinsic::returnaddress
:
743 case Intrinsic::frameaddress
:
744 cerr
<< "WARNING: this target does not support the llvm."
745 << (Callee
->getIntrinsicID() == Intrinsic::returnaddress
?
746 "return" : "frame") << "address intrinsic.\n";
747 CI
->replaceAllUsesWith(ConstantPointerNull::get(
748 cast
<PointerType
>(CI
->getType())));
751 case Intrinsic::prefetch
:
752 break; // Simply strip out prefetches on unsupported architectures
754 case Intrinsic::pcmarker
:
755 break; // Simply strip out pcmarker on unsupported architectures
756 case Intrinsic::readcyclecounter
: {
757 cerr
<< "WARNING: this target does not support the llvm.readcyclecoun"
758 << "ter intrinsic. It is being lowered to a constant 0\n";
759 CI
->replaceAllUsesWith(ConstantInt::get(Type::Int64Ty
, 0));
763 case Intrinsic::dbg_stoppoint
:
764 case Intrinsic::dbg_region_start
:
765 case Intrinsic::dbg_region_end
:
766 case Intrinsic::dbg_func_start
:
767 case Intrinsic::dbg_declare
:
768 break; // Simply strip out debugging intrinsics
770 case Intrinsic::eh_exception
:
771 case Intrinsic::eh_selector_i32
:
772 case Intrinsic::eh_selector_i64
:
773 CI
->replaceAllUsesWith(Constant::getNullValue(CI
->getType()));
776 case Intrinsic::eh_typeid_for_i32
:
777 case Intrinsic::eh_typeid_for_i64
:
778 // Return something different to eh_selector.
779 CI
->replaceAllUsesWith(ConstantInt::get(CI
->getType(), 1));
782 case Intrinsic::var_annotation
:
783 break; // Strip out annotate intrinsic
785 case Intrinsic::memcpy
: {
786 static Constant
*MemcpyFCache
= 0;
787 const IntegerType
*IntPtr
= TD
.getIntPtrType();
788 Value
*Size
= Builder
.CreateIntCast(CI
->getOperand(3), IntPtr
,
789 /* isSigned */ false);
791 Ops
[0] = CI
->getOperand(1);
792 Ops
[1] = CI
->getOperand(2);
794 ReplaceCallWith("memcpy", CI
, Ops
, Ops
+3, CI
->getOperand(1)->getType(),
798 case Intrinsic::memmove
: {
799 static Constant
*MemmoveFCache
= 0;
800 const IntegerType
*IntPtr
= TD
.getIntPtrType();
801 Value
*Size
= Builder
.CreateIntCast(CI
->getOperand(3), IntPtr
,
802 /* isSigned */ false);
804 Ops
[0] = CI
->getOperand(1);
805 Ops
[1] = CI
->getOperand(2);
807 ReplaceCallWith("memmove", CI
, Ops
, Ops
+3, CI
->getOperand(1)->getType(),
811 case Intrinsic::memset
: {
812 static Constant
*MemsetFCache
= 0;
813 const IntegerType
*IntPtr
= TD
.getIntPtrType();
814 Value
*Size
= Builder
.CreateIntCast(CI
->getOperand(3), IntPtr
,
815 /* isSigned */ false);
817 Ops
[0] = CI
->getOperand(1);
818 // Extend the amount to i32.
819 Ops
[1] = Builder
.CreateIntCast(CI
->getOperand(2), Type::Int32Ty
,
820 /* isSigned */ false);
822 ReplaceCallWith("memset", CI
, Ops
, Ops
+3, CI
->getOperand(1)->getType(),
826 case Intrinsic::sqrt
: {
827 static Constant
*sqrtFCache
= 0;
828 static Constant
*sqrtDCache
= 0;
829 static Constant
*sqrtLDCache
= 0;
830 ReplaceFPIntrinsicWithCall(CI
, sqrtFCache
, sqrtDCache
, sqrtLDCache
,
831 "sqrtf", "sqrt", "sqrtl");
834 case Intrinsic::log
: {
835 static Constant
*logFCache
= 0;
836 static Constant
*logDCache
= 0;
837 static Constant
*logLDCache
= 0;
838 ReplaceFPIntrinsicWithCall(CI
, logFCache
, logDCache
, logLDCache
,
839 "logf", "log", "logl");
842 case Intrinsic::log2
: {
843 static Constant
*log2FCache
= 0;
844 static Constant
*log2DCache
= 0;
845 static Constant
*log2LDCache
= 0;
846 ReplaceFPIntrinsicWithCall(CI
, log2FCache
, log2DCache
, log2LDCache
,
847 "log2f", "log2", "log2l");
850 case Intrinsic::log10
: {
851 static Constant
*log10FCache
= 0;
852 static Constant
*log10DCache
= 0;
853 static Constant
*log10LDCache
= 0;
854 ReplaceFPIntrinsicWithCall(CI
, log10FCache
, log10DCache
, log10LDCache
,
855 "log10f", "log10", "log10l");
858 case Intrinsic::exp
: {
859 static Constant
*expFCache
= 0;
860 static Constant
*expDCache
= 0;
861 static Constant
*expLDCache
= 0;
862 ReplaceFPIntrinsicWithCall(CI
, expFCache
, expDCache
, expLDCache
,
863 "expf", "exp", "expl");
866 case Intrinsic::exp2
: {
867 static Constant
*exp2FCache
= 0;
868 static Constant
*exp2DCache
= 0;
869 static Constant
*exp2LDCache
= 0;
870 ReplaceFPIntrinsicWithCall(CI
, exp2FCache
, exp2DCache
, exp2LDCache
,
871 "exp2f", "exp2", "exp2l");
874 case Intrinsic::pow
: {
875 static Constant
*powFCache
= 0;
876 static Constant
*powDCache
= 0;
877 static Constant
*powLDCache
= 0;
878 ReplaceFPIntrinsicWithCall(CI
, powFCache
, powDCache
, powLDCache
,
879 "powf", "pow", "powl");
882 case Intrinsic::flt_rounds
:
883 // Lower to "round to the nearest"
884 if (CI
->getType() != Type::VoidTy
)
885 CI
->replaceAllUsesWith(ConstantInt::get(CI
->getType(), 1));
889 assert(CI
->use_empty() &&
890 "Lowering should have eliminated any uses of the intrinsic call!");
891 CI
->eraseFromParent();