llvm-stress.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774
  1. //===- llvm-stress.cpp - Generate random LL files to stress-test LLVM -----===//
  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 program is a utility that generates random .ll files to stress-test
  10. // different components in LLVM.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/ADT/APFloat.h"
  14. #include "llvm/ADT/APInt.h"
  15. #include "llvm/ADT/ArrayRef.h"
  16. #include "llvm/ADT/STLExtras.h"
  17. #include "llvm/ADT/StringRef.h"
  18. #include "llvm/ADT/Twine.h"
  19. #include "llvm/IR/BasicBlock.h"
  20. #include "llvm/IR/CallingConv.h"
  21. #include "llvm/IR/Constants.h"
  22. #include "llvm/IR/DataLayout.h"
  23. #include "llvm/IR/DerivedTypes.h"
  24. #include "llvm/IR/Function.h"
  25. #include "llvm/IR/GlobalValue.h"
  26. #include "llvm/IR/InstrTypes.h"
  27. #include "llvm/IR/Instruction.h"
  28. #include "llvm/IR/Instructions.h"
  29. #include "llvm/IR/LLVMContext.h"
  30. #include "llvm/IR/Module.h"
  31. #include "llvm/IR/Type.h"
  32. #include "llvm/IR/Value.h"
  33. #include "llvm/IR/Verifier.h"
  34. #include "llvm/Support/Casting.h"
  35. #include "llvm/Support/CommandLine.h"
  36. #include "llvm/Support/ErrorHandling.h"
  37. #include "llvm/Support/FileSystem.h"
  38. #include "llvm/Support/InitLLVM.h"
  39. #include "llvm/Support/ToolOutputFile.h"
  40. #include "llvm/Support/WithColor.h"
  41. #include "llvm/Support/raw_ostream.h"
  42. #include <algorithm>
  43. #include <cassert>
  44. #include <cstddef>
  45. #include <cstdint>
  46. #include <memory>
  47. #include <string>
  48. #include <system_error>
  49. #include <vector>
  50. namespace llvm {
  51. static cl::OptionCategory StressCategory("Stress Options");
  52. static cl::opt<unsigned> SeedCL("seed", cl::desc("Seed used for randomness"),
  53. cl::init(0), cl::cat(StressCategory));
  54. static cl::opt<unsigned> SizeCL(
  55. "size",
  56. cl::desc("The estimated size of the generated function (# of instrs)"),
  57. cl::init(100), cl::cat(StressCategory));
  58. static cl::opt<std::string> OutputFilename("o",
  59. cl::desc("Override output filename"),
  60. cl::value_desc("filename"),
  61. cl::cat(StressCategory));
  62. static cl::list<StringRef> AdditionalScalarTypes(
  63. "types", cl::CommaSeparated,
  64. cl::desc("Additional IR scalar types "
  65. "(always includes i1, i8, i16, i32, i64, float and double)"));
  66. static cl::opt<bool> EnableScalableVectors(
  67. "enable-scalable-vectors",
  68. cl::desc("Generate IR involving scalable vector types"),
  69. cl::init(false), cl::cat(StressCategory));
  70. namespace {
  71. /// A utility class to provide a pseudo-random number generator which is
  72. /// the same across all platforms. This is somewhat close to the libc
  73. /// implementation. Note: This is not a cryptographically secure pseudorandom
  74. /// number generator.
  75. class Random {
  76. public:
  77. /// C'tor
  78. Random(unsigned _seed):Seed(_seed) {}
  79. /// Return a random integer, up to a
  80. /// maximum of 2**19 - 1.
  81. uint32_t Rand() {
  82. uint32_t Val = Seed + 0x000b07a1;
  83. Seed = (Val * 0x3c7c0ac1);
  84. // Only lowest 19 bits are random-ish.
  85. return Seed & 0x7ffff;
  86. }
  87. /// Return a random 64 bit integer.
  88. uint64_t Rand64() {
  89. uint64_t Val = Rand() & 0xffff;
  90. Val |= uint64_t(Rand() & 0xffff) << 16;
  91. Val |= uint64_t(Rand() & 0xffff) << 32;
  92. Val |= uint64_t(Rand() & 0xffff) << 48;
  93. return Val;
  94. }
  95. /// Rand operator for STL algorithms.
  96. ptrdiff_t operator()(ptrdiff_t y) {
  97. return Rand64() % y;
  98. }
  99. /// Make this like a C++11 random device
  100. using result_type = uint32_t ;
  101. static constexpr result_type min() { return 0; }
  102. static constexpr result_type max() { return 0x7ffff; }
  103. uint32_t operator()() {
  104. uint32_t Val = Rand();
  105. assert(Val <= max() && "Random value out of range");
  106. return Val;
  107. }
  108. private:
  109. unsigned Seed;
  110. };
  111. /// Generate an empty function with a default argument list.
  112. Function *GenEmptyFunction(Module *M) {
  113. // Define a few arguments
  114. LLVMContext &Context = M->getContext();
  115. Type* ArgsTy[] = {
  116. Type::getInt8PtrTy(Context),
  117. Type::getInt32PtrTy(Context),
  118. Type::getInt64PtrTy(Context),
  119. Type::getInt32Ty(Context),
  120. Type::getInt64Ty(Context),
  121. Type::getInt8Ty(Context)
  122. };
  123. auto *FuncTy = FunctionType::get(Type::getVoidTy(Context), ArgsTy, false);
  124. // Pick a unique name to describe the input parameters
  125. Twine Name = "autogen_SD" + Twine{SeedCL};
  126. auto *Func = Function::Create(FuncTy, GlobalValue::ExternalLinkage, Name, M);
  127. Func->setCallingConv(CallingConv::C);
  128. return Func;
  129. }
  130. /// A base class, implementing utilities needed for
  131. /// modifying and adding new random instructions.
  132. struct Modifier {
  133. /// Used to store the randomly generated values.
  134. using PieceTable = std::vector<Value *>;
  135. public:
  136. /// C'tor
  137. Modifier(BasicBlock *Block, PieceTable *PT, Random *R)
  138. : BB(Block), PT(PT), Ran(R), Context(BB->getContext()) {
  139. ScalarTypes.assign({Type::getInt1Ty(Context), Type::getInt8Ty(Context),
  140. Type::getInt16Ty(Context), Type::getInt32Ty(Context),
  141. Type::getInt64Ty(Context), Type::getFloatTy(Context),
  142. Type::getDoubleTy(Context)});
  143. for (auto &Arg : AdditionalScalarTypes) {
  144. Type *Ty = nullptr;
  145. if (Arg == "half")
  146. Ty = Type::getHalfTy(Context);
  147. else if (Arg == "fp128")
  148. Ty = Type::getFP128Ty(Context);
  149. else if (Arg == "x86_fp80")
  150. Ty = Type::getX86_FP80Ty(Context);
  151. else if (Arg == "ppc_fp128")
  152. Ty = Type::getPPC_FP128Ty(Context);
  153. else if (Arg == "x86_mmx")
  154. Ty = Type::getX86_MMXTy(Context);
  155. else if (Arg.startswith("i")) {
  156. unsigned N = 0;
  157. Arg.drop_front().getAsInteger(10, N);
  158. if (N > 0)
  159. Ty = Type::getIntNTy(Context, N);
  160. }
  161. if (!Ty) {
  162. errs() << "Invalid IR scalar type: '" << Arg << "'!\n";
  163. exit(1);
  164. }
  165. ScalarTypes.push_back(Ty);
  166. }
  167. }
  168. /// virtual D'tor to silence warnings.
  169. virtual ~Modifier() = default;
  170. /// Add a new instruction.
  171. virtual void Act() = 0;
  172. /// Add N new instructions,
  173. virtual void ActN(unsigned n) {
  174. for (unsigned i=0; i<n; ++i)
  175. Act();
  176. }
  177. protected:
  178. /// Return a random integer.
  179. uint32_t getRandom() {
  180. return Ran->Rand();
  181. }
  182. /// Return a random value from the list of known values.
  183. Value *getRandomVal() {
  184. assert(PT->size());
  185. return PT->at(getRandom() % PT->size());
  186. }
  187. Constant *getRandomConstant(Type *Tp) {
  188. if (Tp->isIntegerTy()) {
  189. if (getRandom() & 1)
  190. return ConstantInt::getAllOnesValue(Tp);
  191. return ConstantInt::getNullValue(Tp);
  192. } else if (Tp->isFloatingPointTy()) {
  193. if (getRandom() & 1)
  194. return ConstantFP::getAllOnesValue(Tp);
  195. return ConstantFP::getNullValue(Tp);
  196. }
  197. return UndefValue::get(Tp);
  198. }
  199. /// Return a random value with a known type.
  200. Value *getRandomValue(Type *Tp) {
  201. unsigned index = getRandom();
  202. for (unsigned i=0; i<PT->size(); ++i) {
  203. Value *V = PT->at((index + i) % PT->size());
  204. if (V->getType() == Tp)
  205. return V;
  206. }
  207. // If the requested type was not found, generate a constant value.
  208. if (Tp->isIntegerTy()) {
  209. if (getRandom() & 1)
  210. return ConstantInt::getAllOnesValue(Tp);
  211. return ConstantInt::getNullValue(Tp);
  212. } else if (Tp->isFloatingPointTy()) {
  213. if (getRandom() & 1)
  214. return ConstantFP::getAllOnesValue(Tp);
  215. return ConstantFP::getNullValue(Tp);
  216. } else if (auto *VTp = dyn_cast<FixedVectorType>(Tp)) {
  217. std::vector<Constant*> TempValues;
  218. TempValues.reserve(VTp->getNumElements());
  219. for (unsigned i = 0; i < VTp->getNumElements(); ++i)
  220. TempValues.push_back(getRandomConstant(VTp->getScalarType()));
  221. ArrayRef<Constant*> VectorValue(TempValues);
  222. return ConstantVector::get(VectorValue);
  223. }
  224. return UndefValue::get(Tp);
  225. }
  226. /// Return a random value of any pointer type.
  227. Value *getRandomPointerValue() {
  228. unsigned index = getRandom();
  229. for (unsigned i=0; i<PT->size(); ++i) {
  230. Value *V = PT->at((index + i) % PT->size());
  231. if (V->getType()->isPointerTy())
  232. return V;
  233. }
  234. return UndefValue::get(pickPointerType());
  235. }
  236. /// Return a random value of any vector type.
  237. Value *getRandomVectorValue() {
  238. unsigned index = getRandom();
  239. for (unsigned i=0; i<PT->size(); ++i) {
  240. Value *V = PT->at((index + i) % PT->size());
  241. if (V->getType()->isVectorTy())
  242. return V;
  243. }
  244. return UndefValue::get(pickVectorType());
  245. }
  246. /// Pick a random type.
  247. Type *pickType() {
  248. return (getRandom() & 1) ? pickVectorType() : pickScalarType();
  249. }
  250. /// Pick a random pointer type.
  251. Type *pickPointerType() {
  252. Type *Ty = pickType();
  253. return PointerType::get(Ty, 0);
  254. }
  255. /// Pick a random vector type.
  256. Type *pickVectorType(VectorType *VTy = nullptr) {
  257. // Vectors of x86mmx are illegal; keep trying till we get something else.
  258. Type *Ty;
  259. do {
  260. Ty = pickScalarType();
  261. } while (Ty->isX86_MMXTy());
  262. if (VTy)
  263. return VectorType::get(Ty, VTy->getElementCount());
  264. // Select either fixed length or scalable vectors with 50% probability
  265. // (only if scalable vectors are enabled)
  266. bool Scalable = EnableScalableVectors && getRandom() & 1;
  267. // Pick a random vector width in the range 2**0 to 2**4.
  268. // by adding two randoms we are generating a normal-like distribution
  269. // around 2**3.
  270. unsigned width = 1<<((getRandom() % 3) + (getRandom() % 3));
  271. return VectorType::get(Ty, width, Scalable);
  272. }
  273. /// Pick a random scalar type.
  274. Type *pickScalarType() {
  275. return ScalarTypes[getRandom() % ScalarTypes.size()];
  276. }
  277. /// Basic block to populate
  278. BasicBlock *BB;
  279. /// Value table
  280. PieceTable *PT;
  281. /// Random number generator
  282. Random *Ran;
  283. /// Context
  284. LLVMContext &Context;
  285. std::vector<Type *> ScalarTypes;
  286. };
  287. struct LoadModifier: public Modifier {
  288. LoadModifier(BasicBlock *BB, PieceTable *PT, Random *R)
  289. : Modifier(BB, PT, R) {}
  290. void Act() override {
  291. // Try to use predefined pointers. If non-exist, use undef pointer value;
  292. Value *Ptr = getRandomPointerValue();
  293. Type *Ty = Ptr->getType()->isOpaquePointerTy()
  294. ? pickType()
  295. : Ptr->getType()->getNonOpaquePointerElementType();
  296. Value *V = new LoadInst(Ty, Ptr, "L", BB->getTerminator());
  297. PT->push_back(V);
  298. }
  299. };
  300. struct StoreModifier: public Modifier {
  301. StoreModifier(BasicBlock *BB, PieceTable *PT, Random *R)
  302. : Modifier(BB, PT, R) {}
  303. void Act() override {
  304. // Try to use predefined pointers. If non-exist, use undef pointer value;
  305. Value *Ptr = getRandomPointerValue();
  306. Type *ValTy = Ptr->getType()->isOpaquePointerTy()
  307. ? pickType()
  308. : Ptr->getType()->getNonOpaquePointerElementType();
  309. // Do not store vectors of i1s because they are unsupported
  310. // by the codegen.
  311. if (ValTy->isVectorTy() && ValTy->getScalarSizeInBits() == 1)
  312. return;
  313. Value *Val = getRandomValue(ValTy);
  314. new StoreInst(Val, Ptr, BB->getTerminator());
  315. }
  316. };
  317. struct BinModifier: public Modifier {
  318. BinModifier(BasicBlock *BB, PieceTable *PT, Random *R)
  319. : Modifier(BB, PT, R) {}
  320. void Act() override {
  321. Value *Val0 = getRandomVal();
  322. Value *Val1 = getRandomValue(Val0->getType());
  323. // Don't handle pointer types.
  324. if (Val0->getType()->isPointerTy() ||
  325. Val1->getType()->isPointerTy())
  326. return;
  327. // Don't handle i1 types.
  328. if (Val0->getType()->getScalarSizeInBits() == 1)
  329. return;
  330. bool isFloat = Val0->getType()->getScalarType()->isFloatingPointTy();
  331. Instruction* Term = BB->getTerminator();
  332. unsigned R = getRandom() % (isFloat ? 7 : 13);
  333. Instruction::BinaryOps Op;
  334. switch (R) {
  335. default: llvm_unreachable("Invalid BinOp");
  336. case 0:{Op = (isFloat?Instruction::FAdd : Instruction::Add); break; }
  337. case 1:{Op = (isFloat?Instruction::FSub : Instruction::Sub); break; }
  338. case 2:{Op = (isFloat?Instruction::FMul : Instruction::Mul); break; }
  339. case 3:{Op = (isFloat?Instruction::FDiv : Instruction::SDiv); break; }
  340. case 4:{Op = (isFloat?Instruction::FDiv : Instruction::UDiv); break; }
  341. case 5:{Op = (isFloat?Instruction::FRem : Instruction::SRem); break; }
  342. case 6:{Op = (isFloat?Instruction::FRem : Instruction::URem); break; }
  343. case 7: {Op = Instruction::Shl; break; }
  344. case 8: {Op = Instruction::LShr; break; }
  345. case 9: {Op = Instruction::AShr; break; }
  346. case 10:{Op = Instruction::And; break; }
  347. case 11:{Op = Instruction::Or; break; }
  348. case 12:{Op = Instruction::Xor; break; }
  349. }
  350. PT->push_back(BinaryOperator::Create(Op, Val0, Val1, "B", Term));
  351. }
  352. };
  353. /// Generate constant values.
  354. struct ConstModifier: public Modifier {
  355. ConstModifier(BasicBlock *BB, PieceTable *PT, Random *R)
  356. : Modifier(BB, PT, R) {}
  357. void Act() override {
  358. Type *Ty = pickType();
  359. if (Ty->isVectorTy()) {
  360. switch (getRandom() % 2) {
  361. case 0: if (Ty->isIntOrIntVectorTy())
  362. return PT->push_back(ConstantVector::getAllOnesValue(Ty));
  363. break;
  364. case 1: if (Ty->isIntOrIntVectorTy())
  365. return PT->push_back(ConstantVector::getNullValue(Ty));
  366. }
  367. }
  368. if (Ty->isFloatingPointTy()) {
  369. // Generate 128 random bits, the size of the (currently)
  370. // largest floating-point types.
  371. uint64_t RandomBits[2];
  372. for (unsigned i = 0; i < 2; ++i)
  373. RandomBits[i] = Ran->Rand64();
  374. APInt RandomInt(Ty->getPrimitiveSizeInBits(), ArrayRef(RandomBits));
  375. APFloat RandomFloat(Ty->getFltSemantics(), RandomInt);
  376. if (getRandom() & 1)
  377. return PT->push_back(ConstantFP::getNullValue(Ty));
  378. return PT->push_back(ConstantFP::get(Ty->getContext(), RandomFloat));
  379. }
  380. if (Ty->isIntegerTy()) {
  381. switch (getRandom() % 7) {
  382. case 0:
  383. return PT->push_back(ConstantInt::get(
  384. Ty, APInt::getAllOnes(Ty->getPrimitiveSizeInBits())));
  385. case 1:
  386. return PT->push_back(
  387. ConstantInt::get(Ty, APInt::getZero(Ty->getPrimitiveSizeInBits())));
  388. case 2:
  389. case 3:
  390. case 4:
  391. case 5:
  392. case 6:
  393. PT->push_back(ConstantInt::get(Ty, getRandom()));
  394. }
  395. }
  396. }
  397. };
  398. struct AllocaModifier: public Modifier {
  399. AllocaModifier(BasicBlock *BB, PieceTable *PT, Random *R)
  400. : Modifier(BB, PT, R) {}
  401. void Act() override {
  402. Type *Tp = pickType();
  403. const DataLayout &DL = BB->getModule()->getDataLayout();
  404. PT->push_back(new AllocaInst(Tp, DL.getAllocaAddrSpace(),
  405. "A", BB->getFirstNonPHI()));
  406. }
  407. };
  408. struct ExtractElementModifier: public Modifier {
  409. ExtractElementModifier(BasicBlock *BB, PieceTable *PT, Random *R)
  410. : Modifier(BB, PT, R) {}
  411. void Act() override {
  412. Value *Val0 = getRandomVectorValue();
  413. Value *V = ExtractElementInst::Create(
  414. Val0,
  415. getRandomValue(Type::getInt32Ty(BB->getContext())),
  416. "E", BB->getTerminator());
  417. return PT->push_back(V);
  418. }
  419. };
  420. struct ShuffModifier: public Modifier {
  421. ShuffModifier(BasicBlock *BB, PieceTable *PT, Random *R)
  422. : Modifier(BB, PT, R) {}
  423. void Act() override {
  424. Value *Val0 = getRandomVectorValue();
  425. Value *Val1 = getRandomValue(Val0->getType());
  426. // Can't express arbitrary shufflevectors for scalable vectors
  427. if (isa<ScalableVectorType>(Val0->getType()))
  428. return;
  429. unsigned Width = cast<FixedVectorType>(Val0->getType())->getNumElements();
  430. std::vector<Constant*> Idxs;
  431. Type *I32 = Type::getInt32Ty(BB->getContext());
  432. for (unsigned i=0; i<Width; ++i) {
  433. Constant *CI = ConstantInt::get(I32, getRandom() % (Width*2));
  434. // Pick some undef values.
  435. if (!(getRandom() % 5))
  436. CI = UndefValue::get(I32);
  437. Idxs.push_back(CI);
  438. }
  439. Constant *Mask = ConstantVector::get(Idxs);
  440. Value *V = new ShuffleVectorInst(Val0, Val1, Mask, "Shuff",
  441. BB->getTerminator());
  442. PT->push_back(V);
  443. }
  444. };
  445. struct InsertElementModifier: public Modifier {
  446. InsertElementModifier(BasicBlock *BB, PieceTable *PT, Random *R)
  447. : Modifier(BB, PT, R) {}
  448. void Act() override {
  449. Value *Val0 = getRandomVectorValue();
  450. Value *Val1 = getRandomValue(Val0->getType()->getScalarType());
  451. Value *V = InsertElementInst::Create(
  452. Val0, Val1,
  453. getRandomValue(Type::getInt32Ty(BB->getContext())),
  454. "I", BB->getTerminator());
  455. return PT->push_back(V);
  456. }
  457. };
  458. struct CastModifier: public Modifier {
  459. CastModifier(BasicBlock *BB, PieceTable *PT, Random *R)
  460. : Modifier(BB, PT, R) {}
  461. void Act() override {
  462. Value *V = getRandomVal();
  463. Type *VTy = V->getType();
  464. Type *DestTy = pickScalarType();
  465. // Handle vector casts vectors.
  466. if (VTy->isVectorTy())
  467. DestTy = pickVectorType(cast<VectorType>(VTy));
  468. // no need to cast.
  469. if (VTy == DestTy) return;
  470. // Pointers:
  471. if (VTy->isPointerTy()) {
  472. if (!DestTy->isPointerTy())
  473. DestTy = PointerType::get(DestTy, 0);
  474. return PT->push_back(
  475. new BitCastInst(V, DestTy, "PC", BB->getTerminator()));
  476. }
  477. unsigned VSize = VTy->getScalarType()->getPrimitiveSizeInBits();
  478. unsigned DestSize = DestTy->getScalarType()->getPrimitiveSizeInBits();
  479. // Generate lots of bitcasts.
  480. if ((getRandom() & 1) && VSize == DestSize) {
  481. return PT->push_back(
  482. new BitCastInst(V, DestTy, "BC", BB->getTerminator()));
  483. }
  484. // Both types are integers:
  485. if (VTy->isIntOrIntVectorTy() && DestTy->isIntOrIntVectorTy()) {
  486. if (VSize > DestSize) {
  487. return PT->push_back(
  488. new TruncInst(V, DestTy, "Tr", BB->getTerminator()));
  489. } else {
  490. assert(VSize < DestSize && "Different int types with the same size?");
  491. if (getRandom() & 1)
  492. return PT->push_back(
  493. new ZExtInst(V, DestTy, "ZE", BB->getTerminator()));
  494. return PT->push_back(new SExtInst(V, DestTy, "Se", BB->getTerminator()));
  495. }
  496. }
  497. // Fp to int.
  498. if (VTy->isFPOrFPVectorTy() && DestTy->isIntOrIntVectorTy()) {
  499. if (getRandom() & 1)
  500. return PT->push_back(
  501. new FPToSIInst(V, DestTy, "FC", BB->getTerminator()));
  502. return PT->push_back(new FPToUIInst(V, DestTy, "FC", BB->getTerminator()));
  503. }
  504. // Int to fp.
  505. if (VTy->isIntOrIntVectorTy() && DestTy->isFPOrFPVectorTy()) {
  506. if (getRandom() & 1)
  507. return PT->push_back(
  508. new SIToFPInst(V, DestTy, "FC", BB->getTerminator()));
  509. return PT->push_back(new UIToFPInst(V, DestTy, "FC", BB->getTerminator()));
  510. }
  511. // Both floats.
  512. if (VTy->isFPOrFPVectorTy() && DestTy->isFPOrFPVectorTy()) {
  513. if (VSize > DestSize) {
  514. return PT->push_back(
  515. new FPTruncInst(V, DestTy, "Tr", BB->getTerminator()));
  516. } else if (VSize < DestSize) {
  517. return PT->push_back(
  518. new FPExtInst(V, DestTy, "ZE", BB->getTerminator()));
  519. }
  520. // If VSize == DestSize, then the two types must be fp128 and ppc_fp128,
  521. // for which there is no defined conversion. So do nothing.
  522. }
  523. }
  524. };
  525. struct SelectModifier: public Modifier {
  526. SelectModifier(BasicBlock *BB, PieceTable *PT, Random *R)
  527. : Modifier(BB, PT, R) {}
  528. void Act() override {
  529. // Try a bunch of different select configuration until a valid one is found.
  530. Value *Val0 = getRandomVal();
  531. Value *Val1 = getRandomValue(Val0->getType());
  532. Type *CondTy = Type::getInt1Ty(Context);
  533. // If the value type is a vector, and we allow vector select, then in 50%
  534. // of the cases generate a vector select.
  535. if (auto *VTy = dyn_cast<VectorType>(Val0->getType()))
  536. if (getRandom() & 1)
  537. CondTy = VectorType::get(CondTy, VTy->getElementCount());
  538. Value *Cond = getRandomValue(CondTy);
  539. Value *V = SelectInst::Create(Cond, Val0, Val1, "Sl", BB->getTerminator());
  540. return PT->push_back(V);
  541. }
  542. };
  543. struct CmpModifier: public Modifier {
  544. CmpModifier(BasicBlock *BB, PieceTable *PT, Random *R)
  545. : Modifier(BB, PT, R) {}
  546. void Act() override {
  547. Value *Val0 = getRandomVal();
  548. Value *Val1 = getRandomValue(Val0->getType());
  549. if (Val0->getType()->isPointerTy()) return;
  550. bool fp = Val0->getType()->getScalarType()->isFloatingPointTy();
  551. int op;
  552. if (fp) {
  553. op = getRandom() %
  554. (CmpInst::LAST_FCMP_PREDICATE - CmpInst::FIRST_FCMP_PREDICATE) +
  555. CmpInst::FIRST_FCMP_PREDICATE;
  556. } else {
  557. op = getRandom() %
  558. (CmpInst::LAST_ICMP_PREDICATE - CmpInst::FIRST_ICMP_PREDICATE) +
  559. CmpInst::FIRST_ICMP_PREDICATE;
  560. }
  561. Value *V = CmpInst::Create(fp ? Instruction::FCmp : Instruction::ICmp,
  562. (CmpInst::Predicate)op, Val0, Val1, "Cmp",
  563. BB->getTerminator());
  564. return PT->push_back(V);
  565. }
  566. };
  567. } // end anonymous namespace
  568. static void FillFunction(Function *F, Random &R) {
  569. // Create a legal entry block.
  570. BasicBlock *BB = BasicBlock::Create(F->getContext(), "BB", F);
  571. ReturnInst::Create(F->getContext(), BB);
  572. // Create the value table.
  573. Modifier::PieceTable PT;
  574. // Consider arguments as legal values.
  575. for (auto &arg : F->args())
  576. PT.push_back(&arg);
  577. // List of modifiers which add new random instructions.
  578. std::vector<std::unique_ptr<Modifier>> Modifiers;
  579. Modifiers.emplace_back(new LoadModifier(BB, &PT, &R));
  580. Modifiers.emplace_back(new StoreModifier(BB, &PT, &R));
  581. auto SM = Modifiers.back().get();
  582. Modifiers.emplace_back(new ExtractElementModifier(BB, &PT, &R));
  583. Modifiers.emplace_back(new ShuffModifier(BB, &PT, &R));
  584. Modifiers.emplace_back(new InsertElementModifier(BB, &PT, &R));
  585. Modifiers.emplace_back(new BinModifier(BB, &PT, &R));
  586. Modifiers.emplace_back(new CastModifier(BB, &PT, &R));
  587. Modifiers.emplace_back(new SelectModifier(BB, &PT, &R));
  588. Modifiers.emplace_back(new CmpModifier(BB, &PT, &R));
  589. // Generate the random instructions
  590. AllocaModifier{BB, &PT, &R}.ActN(5); // Throw in a few allocas
  591. ConstModifier{BB, &PT, &R}.ActN(40); // Throw in a few constants
  592. for (unsigned i = 0; i < SizeCL / Modifiers.size(); ++i)
  593. for (auto &Mod : Modifiers)
  594. Mod->Act();
  595. SM->ActN(5); // Throw in a few stores.
  596. }
  597. static void IntroduceControlFlow(Function *F, Random &R) {
  598. std::vector<Instruction*> BoolInst;
  599. for (auto &Instr : F->front()) {
  600. if (Instr.getType() == IntegerType::getInt1Ty(F->getContext()))
  601. BoolInst.push_back(&Instr);
  602. }
  603. llvm::shuffle(BoolInst.begin(), BoolInst.end(), R);
  604. for (auto *Instr : BoolInst) {
  605. BasicBlock *Curr = Instr->getParent();
  606. BasicBlock::iterator Loc = Instr->getIterator();
  607. BasicBlock *Next = Curr->splitBasicBlock(Loc, "CF");
  608. Instr->moveBefore(Curr->getTerminator());
  609. if (Curr != &F->getEntryBlock()) {
  610. BranchInst::Create(Curr, Next, Instr, Curr->getTerminator());
  611. Curr->getTerminator()->eraseFromParent();
  612. }
  613. }
  614. }
  615. } // end namespace llvm
  616. int main(int argc, char **argv) {
  617. using namespace llvm;
  618. InitLLVM X(argc, argv);
  619. cl::HideUnrelatedOptions({&StressCategory, &getColorCategory()});
  620. cl::ParseCommandLineOptions(argc, argv, "llvm codegen stress-tester\n");
  621. LLVMContext Context;
  622. auto M = std::make_unique<Module>("/tmp/autogen.bc", Context);
  623. Function *F = GenEmptyFunction(M.get());
  624. // Pick an initial seed value
  625. Random R(SeedCL);
  626. // Generate lots of random instructions inside a single basic block.
  627. FillFunction(F, R);
  628. // Break the basic block into many loops.
  629. IntroduceControlFlow(F, R);
  630. // Figure out what stream we are supposed to write to...
  631. std::unique_ptr<ToolOutputFile> Out;
  632. // Default to standard output.
  633. if (OutputFilename.empty())
  634. OutputFilename = "-";
  635. std::error_code EC;
  636. Out.reset(new ToolOutputFile(OutputFilename, EC, sys::fs::OF_None));
  637. if (EC) {
  638. errs() << EC.message() << '\n';
  639. return 1;
  640. }
  641. // Check that the generated module is accepted by the verifier.
  642. if (verifyModule(*M.get(), &Out->os()))
  643. report_fatal_error("Broken module found, compilation aborted!");
  644. // Output textual IR.
  645. M->print(Out->os(), nullptr);
  646. Out->keep();
  647. return 0;
  648. }