IntrinsicLowering.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. //===-- IntrinsicLowering.cpp - Intrinsic Lowering default implementation -===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the IntrinsicLowering class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/CodeGen/IntrinsicLowering.h"
  13. #include "llvm/ADT/SmallVector.h"
  14. #include "llvm/IR/CallSite.h"
  15. #include "llvm/IR/Constants.h"
  16. #include "llvm/IR/DataLayout.h"
  17. #include "llvm/IR/DerivedTypes.h"
  18. #include "llvm/IR/IRBuilder.h"
  19. #include "llvm/IR/Module.h"
  20. #include "llvm/IR/Type.h"
  21. #include "llvm/Support/ErrorHandling.h"
  22. #include "llvm/Support/raw_ostream.h"
  23. using namespace llvm;
  24. /// This function is used when we want to lower an intrinsic call to a call of
  25. /// an external function. This handles hard cases such as when there was already
  26. /// a prototype for the external function, but that prototype doesn't match the
  27. /// arguments we expect to pass in.
  28. template <class ArgIt>
  29. static CallInst *ReplaceCallWith(const char *NewFn, CallInst *CI,
  30. ArgIt ArgBegin, ArgIt ArgEnd,
  31. Type *RetTy) {
  32. // If we haven't already looked up this function, check to see if the
  33. // program already contains a function with this name.
  34. Module *M = CI->getModule();
  35. // Get or insert the definition now.
  36. std::vector<Type *> ParamTys;
  37. for (ArgIt I = ArgBegin; I != ArgEnd; ++I)
  38. ParamTys.push_back((*I)->getType());
  39. FunctionCallee FCache =
  40. M->getOrInsertFunction(NewFn, FunctionType::get(RetTy, ParamTys, false));
  41. IRBuilder<> Builder(CI->getParent(), CI->getIterator());
  42. SmallVector<Value *, 8> Args(ArgBegin, ArgEnd);
  43. CallInst *NewCI = Builder.CreateCall(FCache, Args);
  44. NewCI->setName(CI->getName());
  45. if (!CI->use_empty())
  46. CI->replaceAllUsesWith(NewCI);
  47. return NewCI;
  48. }
  49. // VisualStudio defines setjmp as _setjmp
  50. #if defined(_MSC_VER) && defined(setjmp) && \
  51. !defined(setjmp_undefined_for_msvc)
  52. # pragma push_macro("setjmp")
  53. # undef setjmp
  54. # define setjmp_undefined_for_msvc
  55. #endif
  56. /// Emit the code to lower bswap of V before the specified instruction IP.
  57. static Value *LowerBSWAP(LLVMContext &Context, Value *V, Instruction *IP) {
  58. assert(V->getType()->isIntOrIntVectorTy() && "Can't bswap a non-integer type!");
  59. unsigned BitSize = V->getType()->getScalarSizeInBits();
  60. IRBuilder<> Builder(IP);
  61. switch(BitSize) {
  62. default: llvm_unreachable("Unhandled type size of value to byteswap!");
  63. case 16: {
  64. Value *Tmp1 = Builder.CreateShl(V, ConstantInt::get(V->getType(), 8),
  65. "bswap.2");
  66. Value *Tmp2 = Builder.CreateLShr(V, ConstantInt::get(V->getType(), 8),
  67. "bswap.1");
  68. V = Builder.CreateOr(Tmp1, Tmp2, "bswap.i16");
  69. break;
  70. }
  71. case 32: {
  72. Value *Tmp4 = Builder.CreateShl(V, ConstantInt::get(V->getType(), 24),
  73. "bswap.4");
  74. Value *Tmp3 = Builder.CreateShl(V, ConstantInt::get(V->getType(), 8),
  75. "bswap.3");
  76. Value *Tmp2 = Builder.CreateLShr(V, ConstantInt::get(V->getType(), 8),
  77. "bswap.2");
  78. Value *Tmp1 = Builder.CreateLShr(V,ConstantInt::get(V->getType(), 24),
  79. "bswap.1");
  80. Tmp3 = Builder.CreateAnd(Tmp3,
  81. ConstantInt::get(V->getType(), 0xFF0000),
  82. "bswap.and3");
  83. Tmp2 = Builder.CreateAnd(Tmp2,
  84. ConstantInt::get(V->getType(), 0xFF00),
  85. "bswap.and2");
  86. Tmp4 = Builder.CreateOr(Tmp4, Tmp3, "bswap.or1");
  87. Tmp2 = Builder.CreateOr(Tmp2, Tmp1, "bswap.or2");
  88. V = Builder.CreateOr(Tmp4, Tmp2, "bswap.i32");
  89. break;
  90. }
  91. case 64: {
  92. Value *Tmp8 = Builder.CreateShl(V, ConstantInt::get(V->getType(), 56),
  93. "bswap.8");
  94. Value *Tmp7 = Builder.CreateShl(V, ConstantInt::get(V->getType(), 40),
  95. "bswap.7");
  96. Value *Tmp6 = Builder.CreateShl(V, ConstantInt::get(V->getType(), 24),
  97. "bswap.6");
  98. Value *Tmp5 = Builder.CreateShl(V, ConstantInt::get(V->getType(), 8),
  99. "bswap.5");
  100. Value* Tmp4 = Builder.CreateLShr(V, ConstantInt::get(V->getType(), 8),
  101. "bswap.4");
  102. Value* Tmp3 = Builder.CreateLShr(V,
  103. ConstantInt::get(V->getType(), 24),
  104. "bswap.3");
  105. Value* Tmp2 = Builder.CreateLShr(V,
  106. ConstantInt::get(V->getType(), 40),
  107. "bswap.2");
  108. Value* Tmp1 = Builder.CreateLShr(V,
  109. ConstantInt::get(V->getType(), 56),
  110. "bswap.1");
  111. Tmp7 = Builder.CreateAnd(Tmp7,
  112. ConstantInt::get(V->getType(),
  113. 0xFF000000000000ULL),
  114. "bswap.and7");
  115. Tmp6 = Builder.CreateAnd(Tmp6,
  116. ConstantInt::get(V->getType(),
  117. 0xFF0000000000ULL),
  118. "bswap.and6");
  119. Tmp5 = Builder.CreateAnd(Tmp5,
  120. ConstantInt::get(V->getType(),
  121. 0xFF00000000ULL),
  122. "bswap.and5");
  123. Tmp4 = Builder.CreateAnd(Tmp4,
  124. ConstantInt::get(V->getType(),
  125. 0xFF000000ULL),
  126. "bswap.and4");
  127. Tmp3 = Builder.CreateAnd(Tmp3,
  128. ConstantInt::get(V->getType(),
  129. 0xFF0000ULL),
  130. "bswap.and3");
  131. Tmp2 = Builder.CreateAnd(Tmp2,
  132. ConstantInt::get(V->getType(),
  133. 0xFF00ULL),
  134. "bswap.and2");
  135. Tmp8 = Builder.CreateOr(Tmp8, Tmp7, "bswap.or1");
  136. Tmp6 = Builder.CreateOr(Tmp6, Tmp5, "bswap.or2");
  137. Tmp4 = Builder.CreateOr(Tmp4, Tmp3, "bswap.or3");
  138. Tmp2 = Builder.CreateOr(Tmp2, Tmp1, "bswap.or4");
  139. Tmp8 = Builder.CreateOr(Tmp8, Tmp6, "bswap.or5");
  140. Tmp4 = Builder.CreateOr(Tmp4, Tmp2, "bswap.or6");
  141. V = Builder.CreateOr(Tmp8, Tmp4, "bswap.i64");
  142. break;
  143. }
  144. }
  145. return V;
  146. }
  147. /// Emit the code to lower ctpop of V before the specified instruction IP.
  148. static Value *LowerCTPOP(LLVMContext &Context, Value *V, Instruction *IP) {
  149. assert(V->getType()->isIntegerTy() && "Can't ctpop a non-integer type!");
  150. static const uint64_t MaskValues[6] = {
  151. 0x5555555555555555ULL, 0x3333333333333333ULL,
  152. 0x0F0F0F0F0F0F0F0FULL, 0x00FF00FF00FF00FFULL,
  153. 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL
  154. };
  155. IRBuilder<> Builder(IP);
  156. unsigned BitSize = V->getType()->getPrimitiveSizeInBits();
  157. unsigned WordSize = (BitSize + 63) / 64;
  158. Value *Count = ConstantInt::get(V->getType(), 0);
  159. for (unsigned n = 0; n < WordSize; ++n) {
  160. Value *PartValue = V;
  161. for (unsigned i = 1, ct = 0; i < (BitSize>64 ? 64 : BitSize);
  162. i <<= 1, ++ct) {
  163. Value *MaskCst = ConstantInt::get(V->getType(), MaskValues[ct]);
  164. Value *LHS = Builder.CreateAnd(PartValue, MaskCst, "cppop.and1");
  165. Value *VShift = Builder.CreateLShr(PartValue,
  166. ConstantInt::get(V->getType(), i),
  167. "ctpop.sh");
  168. Value *RHS = Builder.CreateAnd(VShift, MaskCst, "cppop.and2");
  169. PartValue = Builder.CreateAdd(LHS, RHS, "ctpop.step");
  170. }
  171. Count = Builder.CreateAdd(PartValue, Count, "ctpop.part");
  172. if (BitSize > 64) {
  173. V = Builder.CreateLShr(V, ConstantInt::get(V->getType(), 64),
  174. "ctpop.part.sh");
  175. BitSize -= 64;
  176. }
  177. }
  178. return Count;
  179. }
  180. /// Emit the code to lower ctlz of V before the specified instruction IP.
  181. static Value *LowerCTLZ(LLVMContext &Context, Value *V, Instruction *IP) {
  182. IRBuilder<> Builder(IP);
  183. unsigned BitSize = V->getType()->getPrimitiveSizeInBits();
  184. for (unsigned i = 1; i < BitSize; i <<= 1) {
  185. Value *ShVal = ConstantInt::get(V->getType(), i);
  186. ShVal = Builder.CreateLShr(V, ShVal, "ctlz.sh");
  187. V = Builder.CreateOr(V, ShVal, "ctlz.step");
  188. }
  189. V = Builder.CreateNot(V);
  190. return LowerCTPOP(Context, V, IP);
  191. }
  192. static void ReplaceFPIntrinsicWithCall(CallInst *CI, const char *Fname,
  193. const char *Dname,
  194. const char *LDname) {
  195. CallSite CS(CI);
  196. switch (CI->getArgOperand(0)->getType()->getTypeID()) {
  197. default: llvm_unreachable("Invalid type in intrinsic");
  198. case Type::FloatTyID:
  199. ReplaceCallWith(Fname, CI, CS.arg_begin(), CS.arg_end(),
  200. Type::getFloatTy(CI->getContext()));
  201. break;
  202. case Type::DoubleTyID:
  203. ReplaceCallWith(Dname, CI, CS.arg_begin(), CS.arg_end(),
  204. Type::getDoubleTy(CI->getContext()));
  205. break;
  206. case Type::X86_FP80TyID:
  207. case Type::FP128TyID:
  208. case Type::PPC_FP128TyID:
  209. ReplaceCallWith(LDname, CI, CS.arg_begin(), CS.arg_end(),
  210. CI->getArgOperand(0)->getType());
  211. break;
  212. }
  213. }
  214. void IntrinsicLowering::LowerIntrinsicCall(CallInst *CI) {
  215. IRBuilder<> Builder(CI);
  216. LLVMContext &Context = CI->getContext();
  217. const Function *Callee = CI->getCalledFunction();
  218. assert(Callee && "Cannot lower an indirect call!");
  219. CallSite CS(CI);
  220. switch (Callee->getIntrinsicID()) {
  221. case Intrinsic::not_intrinsic:
  222. report_fatal_error("Cannot lower a call to a non-intrinsic function '"+
  223. Callee->getName() + "'!");
  224. default:
  225. report_fatal_error("Code generator does not support intrinsic function '"+
  226. Callee->getName()+"'!");
  227. case Intrinsic::expect: {
  228. // Just replace __builtin_expect(exp, c) with EXP.
  229. Value *V = CI->getArgOperand(0);
  230. CI->replaceAllUsesWith(V);
  231. break;
  232. }
  233. // The setjmp/longjmp intrinsics should only exist in the code if it was
  234. // never optimized (ie, right out of the CFE), or if it has been hacked on
  235. // by the lowerinvoke pass. In both cases, the right thing to do is to
  236. // convert the call to an explicit setjmp or longjmp call.
  237. case Intrinsic::setjmp: {
  238. Value *V = ReplaceCallWith("setjmp", CI, CS.arg_begin(), CS.arg_end(),
  239. Type::getInt32Ty(Context));
  240. if (!CI->getType()->isVoidTy())
  241. CI->replaceAllUsesWith(V);
  242. break;
  243. }
  244. case Intrinsic::sigsetjmp:
  245. if (!CI->getType()->isVoidTy())
  246. CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
  247. break;
  248. case Intrinsic::longjmp: {
  249. ReplaceCallWith("longjmp", CI, CS.arg_begin(), CS.arg_end(),
  250. Type::getVoidTy(Context));
  251. break;
  252. }
  253. case Intrinsic::siglongjmp: {
  254. // Insert the call to abort
  255. ReplaceCallWith("abort", CI, CS.arg_end(), CS.arg_end(),
  256. Type::getVoidTy(Context));
  257. break;
  258. }
  259. case Intrinsic::ctpop:
  260. CI->replaceAllUsesWith(LowerCTPOP(Context, CI->getArgOperand(0), CI));
  261. break;
  262. case Intrinsic::bswap:
  263. CI->replaceAllUsesWith(LowerBSWAP(Context, CI->getArgOperand(0), CI));
  264. break;
  265. case Intrinsic::ctlz:
  266. CI->replaceAllUsesWith(LowerCTLZ(Context, CI->getArgOperand(0), CI));
  267. break;
  268. case Intrinsic::cttz: {
  269. // cttz(x) -> ctpop(~X & (X-1))
  270. Value *Src = CI->getArgOperand(0);
  271. Value *NotSrc = Builder.CreateNot(Src);
  272. NotSrc->setName(Src->getName() + ".not");
  273. Value *SrcM1 = ConstantInt::get(Src->getType(), 1);
  274. SrcM1 = Builder.CreateSub(Src, SrcM1);
  275. Src = LowerCTPOP(Context, Builder.CreateAnd(NotSrc, SrcM1), CI);
  276. CI->replaceAllUsesWith(Src);
  277. break;
  278. }
  279. case Intrinsic::stacksave:
  280. case Intrinsic::stackrestore: {
  281. if (!Warned)
  282. errs() << "WARNING: this target does not support the llvm.stack"
  283. << (Callee->getIntrinsicID() == Intrinsic::stacksave ?
  284. "save" : "restore") << " intrinsic.\n";
  285. Warned = true;
  286. if (Callee->getIntrinsicID() == Intrinsic::stacksave)
  287. CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
  288. break;
  289. }
  290. case Intrinsic::get_dynamic_area_offset:
  291. errs() << "WARNING: this target does not support the custom llvm.get."
  292. "dynamic.area.offset. It is being lowered to a constant 0\n";
  293. // Just lower it to a constant 0 because for most targets
  294. // @llvm.get.dynamic.area.offset is lowered to zero.
  295. CI->replaceAllUsesWith(ConstantInt::get(CI->getType(), 0));
  296. break;
  297. case Intrinsic::returnaddress:
  298. case Intrinsic::frameaddress:
  299. errs() << "WARNING: this target does not support the llvm."
  300. << (Callee->getIntrinsicID() == Intrinsic::returnaddress ?
  301. "return" : "frame") << "address intrinsic.\n";
  302. CI->replaceAllUsesWith(
  303. ConstantPointerNull::get(cast<PointerType>(CI->getType())));
  304. break;
  305. case Intrinsic::addressofreturnaddress:
  306. errs() << "WARNING: this target does not support the "
  307. "llvm.addressofreturnaddress intrinsic.\n";
  308. CI->replaceAllUsesWith(
  309. ConstantPointerNull::get(cast<PointerType>(CI->getType())));
  310. break;
  311. case Intrinsic::prefetch:
  312. break; // Simply strip out prefetches on unsupported architectures
  313. case Intrinsic::pcmarker:
  314. break; // Simply strip out pcmarker on unsupported architectures
  315. case Intrinsic::readcyclecounter: {
  316. errs() << "WARNING: this target does not support the llvm.readcyclecoun"
  317. << "ter intrinsic. It is being lowered to a constant 0\n";
  318. CI->replaceAllUsesWith(ConstantInt::get(Type::getInt64Ty(Context), 0));
  319. break;
  320. }
  321. case Intrinsic::dbg_declare:
  322. case Intrinsic::dbg_label:
  323. break; // Simply strip out debugging intrinsics
  324. case Intrinsic::eh_typeid_for:
  325. // Return something different to eh_selector.
  326. CI->replaceAllUsesWith(ConstantInt::get(CI->getType(), 1));
  327. break;
  328. case Intrinsic::annotation:
  329. case Intrinsic::ptr_annotation:
  330. // Just drop the annotation, but forward the value
  331. CI->replaceAllUsesWith(CI->getOperand(0));
  332. break;
  333. case Intrinsic::assume:
  334. case Intrinsic::var_annotation:
  335. break; // Strip out these intrinsics
  336. case Intrinsic::memcpy: {
  337. Type *IntPtr = DL.getIntPtrType(Context);
  338. Value *Size = Builder.CreateIntCast(CI->getArgOperand(2), IntPtr,
  339. /* isSigned */ false);
  340. Value *Ops[3];
  341. Ops[0] = CI->getArgOperand(0);
  342. Ops[1] = CI->getArgOperand(1);
  343. Ops[2] = Size;
  344. ReplaceCallWith("memcpy", CI, Ops, Ops+3, CI->getArgOperand(0)->getType());
  345. break;
  346. }
  347. case Intrinsic::memmove: {
  348. Type *IntPtr = DL.getIntPtrType(Context);
  349. Value *Size = Builder.CreateIntCast(CI->getArgOperand(2), IntPtr,
  350. /* isSigned */ false);
  351. Value *Ops[3];
  352. Ops[0] = CI->getArgOperand(0);
  353. Ops[1] = CI->getArgOperand(1);
  354. Ops[2] = Size;
  355. ReplaceCallWith("memmove", CI, Ops, Ops+3, CI->getArgOperand(0)->getType());
  356. break;
  357. }
  358. case Intrinsic::memset: {
  359. Value *Op0 = CI->getArgOperand(0);
  360. Type *IntPtr = DL.getIntPtrType(Op0->getType());
  361. Value *Size = Builder.CreateIntCast(CI->getArgOperand(2), IntPtr,
  362. /* isSigned */ false);
  363. Value *Ops[3];
  364. Ops[0] = Op0;
  365. // Extend the amount to i32.
  366. Ops[1] = Builder.CreateIntCast(CI->getArgOperand(1),
  367. Type::getInt32Ty(Context),
  368. /* isSigned */ false);
  369. Ops[2] = Size;
  370. ReplaceCallWith("memset", CI, Ops, Ops+3, CI->getArgOperand(0)->getType());
  371. break;
  372. }
  373. case Intrinsic::sqrt: {
  374. ReplaceFPIntrinsicWithCall(CI, "sqrtf", "sqrt", "sqrtl");
  375. break;
  376. }
  377. case Intrinsic::log: {
  378. ReplaceFPIntrinsicWithCall(CI, "logf", "log", "logl");
  379. break;
  380. }
  381. case Intrinsic::log2: {
  382. ReplaceFPIntrinsicWithCall(CI, "log2f", "log2", "log2l");
  383. break;
  384. }
  385. case Intrinsic::log10: {
  386. ReplaceFPIntrinsicWithCall(CI, "log10f", "log10", "log10l");
  387. break;
  388. }
  389. case Intrinsic::exp: {
  390. ReplaceFPIntrinsicWithCall(CI, "expf", "exp", "expl");
  391. break;
  392. }
  393. case Intrinsic::exp2: {
  394. ReplaceFPIntrinsicWithCall(CI, "exp2f", "exp2", "exp2l");
  395. break;
  396. }
  397. case Intrinsic::pow: {
  398. ReplaceFPIntrinsicWithCall(CI, "powf", "pow", "powl");
  399. break;
  400. }
  401. case Intrinsic::sin: {
  402. ReplaceFPIntrinsicWithCall(CI, "sinf", "sin", "sinl");
  403. break;
  404. }
  405. case Intrinsic::cos: {
  406. ReplaceFPIntrinsicWithCall(CI, "cosf", "cos", "cosl");
  407. break;
  408. }
  409. case Intrinsic::floor: {
  410. ReplaceFPIntrinsicWithCall(CI, "floorf", "floor", "floorl");
  411. break;
  412. }
  413. case Intrinsic::ceil: {
  414. ReplaceFPIntrinsicWithCall(CI, "ceilf", "ceil", "ceill");
  415. break;
  416. }
  417. case Intrinsic::trunc: {
  418. ReplaceFPIntrinsicWithCall(CI, "truncf", "trunc", "truncl");
  419. break;
  420. }
  421. case Intrinsic::round: {
  422. ReplaceFPIntrinsicWithCall(CI, "roundf", "round", "roundl");
  423. break;
  424. }
  425. case Intrinsic::copysign: {
  426. ReplaceFPIntrinsicWithCall(CI, "copysignf", "copysign", "copysignl");
  427. break;
  428. }
  429. case Intrinsic::flt_rounds:
  430. // Lower to "round to the nearest"
  431. if (!CI->getType()->isVoidTy())
  432. CI->replaceAllUsesWith(ConstantInt::get(CI->getType(), 1));
  433. break;
  434. case Intrinsic::invariant_start:
  435. case Intrinsic::lifetime_start:
  436. // Discard region information.
  437. CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
  438. break;
  439. case Intrinsic::invariant_end:
  440. case Intrinsic::lifetime_end:
  441. // Discard region information.
  442. break;
  443. }
  444. assert(CI->use_empty() &&
  445. "Lowering should have eliminated any uses of the intrinsic call!");
  446. CI->eraseFromParent();
  447. }
  448. bool IntrinsicLowering::LowerToByteSwap(CallInst *CI) {
  449. // Verify this is a simple bswap.
  450. if (CI->getNumArgOperands() != 1 ||
  451. CI->getType() != CI->getArgOperand(0)->getType() ||
  452. !CI->getType()->isIntegerTy())
  453. return false;
  454. IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
  455. if (!Ty)
  456. return false;
  457. // Okay, we can do this xform, do so now.
  458. Module *M = CI->getModule();
  459. Function *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Ty);
  460. Value *Op = CI->getArgOperand(0);
  461. Op = CallInst::Create(Int, Op, CI->getName(), CI);
  462. CI->replaceAllUsesWith(Op);
  463. CI->eraseFromParent();
  464. return true;
  465. }