blob: 6e2b8d305738b60bbff17f4f820944631d4b1cf8 [file] [log] [blame]
Daniel Dunbarbeb34252012-02-29 00:20:33 +00001//===-- llvm-stress.cpp - Generate random LL files to stress-test LLVM ----===//
Nadav Rotem78bda892012-02-26 08:35:53 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This program is a utility that generates random .ll files to stress-test
11// different components in LLVM.
12//
13//===----------------------------------------------------------------------===//
Ahmed Charles56440fd2014-03-06 05:51:42 +000014
Chandler Carruth839a98e2013-01-07 15:26:48 +000015#include "llvm/Analysis/CallGraphSCCPass.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000016#include "llvm/IR/Constants.h"
Chandler Carruthb8ddc702014-01-12 11:10:32 +000017#include "llvm/IR/IRPrintingPasses.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000018#include "llvm/IR/Instruction.h"
Chandler Carruthb8ddc702014-01-12 11:10:32 +000019#include "llvm/IR/LLVMContext.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000020#include "llvm/IR/LegacyPassManager.h"
Chandler Carruth1b69ed82014-03-04 12:32:42 +000021#include "llvm/IR/LegacyPassNameParser.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/Module.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000023#include "llvm/IR/Verifier.h"
Nadav Rotem78bda892012-02-26 08:35:53 +000024#include "llvm/Support/Debug.h"
Benjamin Kramerd59664f2014-04-29 23:26:49 +000025#include "llvm/Support/FileSystem.h"
Nadav Rotem78bda892012-02-26 08:35:53 +000026#include "llvm/Support/ManagedStatic.h"
27#include "llvm/Support/PluginLoader.h"
28#include "llvm/Support/PrettyStackTrace.h"
29#include "llvm/Support/ToolOutputFile.h"
Nadav Rotem78bda892012-02-26 08:35:53 +000030#include <algorithm>
Marshall Clowe9110d72017-02-16 14:37:03 +000031#include <random>
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000032#include <vector>
Pawel Bylicaedb02102015-07-10 10:01:47 +000033
34namespace llvm {
Nadav Rotem78bda892012-02-26 08:35:53 +000035
36static cl::opt<unsigned> SeedCL("seed",
37 cl::desc("Seed used for randomness"), cl::init(0));
38static cl::opt<unsigned> SizeCL("size",
39 cl::desc("The estimated size of the generated function (# of instrs)"),
40 cl::init(100));
41static cl::opt<std::string>
42OutputFilename("o", cl::desc("Override output filename"),
43 cl::value_desc("filename"));
44
Mehdi Amini03b42e42016-04-14 21:59:01 +000045static LLVMContext Context;
46
Pawel Bylicaedb02102015-07-10 10:01:47 +000047namespace cl {
48template <> class parser<Type*> final : public basic_parser<Type*> {
49public:
50 parser(Option &O) : basic_parser(O) {}
51
52 // Parse options as IR types. Return true on error.
53 bool parse(Option &O, StringRef, StringRef Arg, Type *&Value) {
Pawel Bylicaedb02102015-07-10 10:01:47 +000054 if (Arg == "half") Value = Type::getHalfTy(Context);
55 else if (Arg == "fp128") Value = Type::getFP128Ty(Context);
56 else if (Arg == "x86_fp80") Value = Type::getX86_FP80Ty(Context);
57 else if (Arg == "ppc_fp128") Value = Type::getPPC_FP128Ty(Context);
58 else if (Arg == "x86_mmx") Value = Type::getX86_MMXTy(Context);
59 else if (Arg.startswith("i")) {
60 unsigned N = 0;
61 Arg.drop_front().getAsInteger(10, N);
62 if (N > 0)
63 Value = Type::getIntNTy(Context, N);
64 }
65
66 if (!Value)
67 return O.error("Invalid IR scalar type: '" + Arg + "'!");
68 return false;
69 }
70
Mehdi Aminie11b7452016-10-01 03:43:20 +000071 StringRef getValueName() const override { return "IR scalar type"; }
Pawel Bylicaedb02102015-07-10 10:01:47 +000072};
73}
74
75
76static cl::list<Type*> AdditionalScalarTypes("types", cl::CommaSeparated,
77 cl::desc("Additional IR scalar types "
78 "(always includes i1, i8, i16, i32, i64, float and double)"));
Hal Finkelc9474122012-02-27 23:59:33 +000079
Juergen Ributzka05c5a932013-11-19 03:08:35 +000080namespace {
Nadav Rotem78bda892012-02-26 08:35:53 +000081/// A utility class to provide a pseudo-random number generator which is
82/// the same across all platforms. This is somewhat close to the libc
83/// implementation. Note: This is not a cryptographically secure pseudorandom
84/// number generator.
85class Random {
86public:
87 /// C'tor
88 Random(unsigned _seed):Seed(_seed) {}
Dylan Noblesmith68f310d2012-04-10 22:44:51 +000089
90 /// Return a random integer, up to a
91 /// maximum of 2**19 - 1.
92 uint32_t Rand() {
93 uint32_t Val = Seed + 0x000b07a1;
Nadav Rotem78bda892012-02-26 08:35:53 +000094 Seed = (Val * 0x3c7c0ac1);
95 // Only lowest 19 bits are random-ish.
96 return Seed & 0x7ffff;
97 }
98
Dylan Noblesmith68f310d2012-04-10 22:44:51 +000099 /// Return a random 32 bit integer.
100 uint32_t Rand32() {
101 uint32_t Val = Rand();
102 Val &= 0xffff;
103 return Val | (Rand() << 16);
104 }
105
106 /// Return a random 64 bit integer.
107 uint64_t Rand64() {
108 uint64_t Val = Rand32();
109 return Val | (uint64_t(Rand32()) << 32);
110 }
Nadav Rotem0fb74082012-06-21 08:58:15 +0000111
112 /// Rand operator for STL algorithms.
113 ptrdiff_t operator()(ptrdiff_t y) {
114 return Rand64() % y;
115 }
116
Marshall Clowe9110d72017-02-16 14:37:03 +0000117 /// Make this like a C++11 random device
118 typedef uint32_t result_type;
Marshall Clowe9110d72017-02-16 14:37:03 +0000119 static constexpr result_type min() { return 0; }
120 static constexpr result_type max() { return 0x7ffff; }
Simon Pilgrim1158fe92017-06-26 10:16:34 +0000121 uint32_t operator()() {
122 uint32_t Val = Rand();
123 assert(Val <= max() && "Random value out of range");
124 return Val;
125 }
126
Nadav Rotem78bda892012-02-26 08:35:53 +0000127private:
128 unsigned Seed;
129};
130
131/// Generate an empty function with a default argument list.
132Function *GenEmptyFunction(Module *M) {
Nadav Rotem78bda892012-02-26 08:35:53 +0000133 // Define a few arguments
134 LLVMContext &Context = M->getContext();
Pawel Bylica23663472015-06-24 11:49:44 +0000135 Type* ArgsTy[] = {
136 Type::getInt8PtrTy(Context),
137 Type::getInt32PtrTy(Context),
138 Type::getInt64PtrTy(Context),
139 Type::getInt32Ty(Context),
140 Type::getInt64Ty(Context),
141 Type::getInt8Ty(Context)
142 };
Nadav Rotem78bda892012-02-26 08:35:53 +0000143
Pawel Bylica23663472015-06-24 11:49:44 +0000144 auto *FuncTy = FunctionType::get(Type::getVoidTy(Context), ArgsTy, false);
Nadav Rotem78bda892012-02-26 08:35:53 +0000145 // Pick a unique name to describe the input parameters
Pawel Bylica23663472015-06-24 11:49:44 +0000146 Twine Name = "autogen_SD" + Twine{SeedCL};
147 auto *Func = Function::Create(FuncTy, GlobalValue::ExternalLinkage, Name, M);
Nadav Rotem78bda892012-02-26 08:35:53 +0000148 Func->setCallingConv(CallingConv::C);
149 return Func;
150}
151
152/// A base class, implementing utilities needed for
153/// modifying and adding new random instructions.
154struct Modifier {
155 /// Used to store the randomly generated values.
156 typedef std::vector<Value*> PieceTable;
157
158public:
159 /// C'tor
Nadav Rotemdc497b62012-02-26 08:59:25 +0000160 Modifier(BasicBlock *Block, PieceTable *PT, Random *R):
Daniel Dunbarbeb34252012-02-29 00:20:33 +0000161 BB(Block),PT(PT),Ran(R),Context(BB->getContext()) {}
Andrew Trickbecbbbe2012-09-19 05:08:30 +0000162
163 /// virtual D'tor to silence warnings.
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000164 virtual ~Modifier() {}
Andrew Trickbecbbbe2012-09-19 05:08:30 +0000165
Nadav Rotem78bda892012-02-26 08:35:53 +0000166 /// Add a new instruction.
167 virtual void Act() = 0;
168 /// Add N new instructions,
169 virtual void ActN(unsigned n) {
170 for (unsigned i=0; i<n; ++i)
171 Act();
172 }
173
174protected:
175 /// Return a random value from the list of known values.
176 Value *getRandomVal() {
177 assert(PT->size());
178 return PT->at(Ran->Rand() % PT->size());
179 }
180
Nadav Roteme4972dd2012-02-26 13:56:18 +0000181 Constant *getRandomConstant(Type *Tp) {
182 if (Tp->isIntegerTy()) {
183 if (Ran->Rand() & 1)
184 return ConstantInt::getAllOnesValue(Tp);
185 return ConstantInt::getNullValue(Tp);
186 } else if (Tp->isFloatingPointTy()) {
187 if (Ran->Rand() & 1)
188 return ConstantFP::getAllOnesValue(Tp);
189 return ConstantFP::getNullValue(Tp);
190 }
191 return UndefValue::get(Tp);
192 }
193
Nadav Rotem78bda892012-02-26 08:35:53 +0000194 /// Return a random value with a known type.
195 Value *getRandomValue(Type *Tp) {
196 unsigned index = Ran->Rand();
197 for (unsigned i=0; i<PT->size(); ++i) {
198 Value *V = PT->at((index + i) % PT->size());
199 if (V->getType() == Tp)
200 return V;
201 }
202
203 // If the requested type was not found, generate a constant value.
204 if (Tp->isIntegerTy()) {
205 if (Ran->Rand() & 1)
206 return ConstantInt::getAllOnesValue(Tp);
207 return ConstantInt::getNullValue(Tp);
208 } else if (Tp->isFloatingPointTy()) {
209 if (Ran->Rand() & 1)
210 return ConstantFP::getAllOnesValue(Tp);
211 return ConstantFP::getNullValue(Tp);
Nadav Roteme4972dd2012-02-26 13:56:18 +0000212 } else if (Tp->isVectorTy()) {
213 VectorType *VTp = cast<VectorType>(Tp);
214
215 std::vector<Constant*> TempValues;
216 TempValues.reserve(VTp->getNumElements());
217 for (unsigned i = 0; i < VTp->getNumElements(); ++i)
218 TempValues.push_back(getRandomConstant(VTp->getScalarType()));
219
220 ArrayRef<Constant*> VectorValue(TempValues);
221 return ConstantVector::get(VectorValue);
Nadav Rotem78bda892012-02-26 08:35:53 +0000222 }
223
Nadav Rotem78bda892012-02-26 08:35:53 +0000224 return UndefValue::get(Tp);
225 }
226
227 /// Return a random value of any pointer type.
228 Value *getRandomPointerValue() {
229 unsigned index = Ran->Rand();
230 for (unsigned i=0; i<PT->size(); ++i) {
231 Value *V = PT->at((index + i) % PT->size());
232 if (V->getType()->isPointerTy())
233 return V;
234 }
235 return UndefValue::get(pickPointerType());
236 }
237
238 /// Return a random value of any vector type.
239 Value *getRandomVectorValue() {
240 unsigned index = Ran->Rand();
241 for (unsigned i=0; i<PT->size(); ++i) {
242 Value *V = PT->at((index + i) % PT->size());
243 if (V->getType()->isVectorTy())
244 return V;
245 }
246 return UndefValue::get(pickVectorType());
247 }
248
249 /// Pick a random type.
250 Type *pickType() {
251 return (Ran->Rand() & 1 ? pickVectorType() : pickScalarType());
252 }
253
254 /// Pick a random pointer type.
255 Type *pickPointerType() {
256 Type *Ty = pickType();
257 return PointerType::get(Ty, 0);
258 }
259
260 /// Pick a random vector type.
261 Type *pickVectorType(unsigned len = (unsigned)-1) {
Nadav Rotem78bda892012-02-26 08:35:53 +0000262 // Pick a random vector width in the range 2**0 to 2**4.
263 // by adding two randoms we are generating a normal-like distribution
264 // around 2**3.
265 unsigned width = 1<<((Ran->Rand() % 3) + (Ran->Rand() % 3));
Dylan Noblesmith2a592dc2012-04-10 22:44:49 +0000266 Type *Ty;
267
268 // Vectors of x86mmx are illegal; keep trying till we get something else.
269 do {
270 Ty = pickScalarType();
271 } while (Ty->isX86_MMXTy());
272
Nadav Rotem78bda892012-02-26 08:35:53 +0000273 if (len != (unsigned)-1)
274 width = len;
275 return VectorType::get(Ty, width);
276 }
277
278 /// Pick a random scalar type.
279 Type *pickScalarType() {
Pawel Bylicaedb02102015-07-10 10:01:47 +0000280 static std::vector<Type*> ScalarTypes;
281 if (ScalarTypes.empty()) {
282 ScalarTypes.assign({
283 Type::getInt1Ty(Context),
284 Type::getInt8Ty(Context),
285 Type::getInt16Ty(Context),
286 Type::getInt32Ty(Context),
287 Type::getInt64Ty(Context),
288 Type::getFloatTy(Context),
289 Type::getDoubleTy(Context)
290 });
291 ScalarTypes.insert(ScalarTypes.end(),
292 AdditionalScalarTypes.begin(), AdditionalScalarTypes.end());
293 }
Hal Finkelc9474122012-02-27 23:59:33 +0000294
Pawel Bylicaedb02102015-07-10 10:01:47 +0000295 return ScalarTypes[Ran->Rand() % ScalarTypes.size()];
Nadav Rotem78bda892012-02-26 08:35:53 +0000296 }
297
298 /// Basic block to populate
299 BasicBlock *BB;
300 /// Value table
301 PieceTable *PT;
302 /// Random number generator
303 Random *Ran;
304 /// Context
305 LLVMContext &Context;
306};
307
308struct LoadModifier: public Modifier {
Daniel Dunbarbeb34252012-02-29 00:20:33 +0000309 LoadModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
Craig Toppere56917c2014-03-08 08:27:28 +0000310 void Act() override {
Alp Tokerf907b892013-12-05 05:44:44 +0000311 // Try to use predefined pointers. If non-exist, use undef pointer value;
Nadav Rotem78bda892012-02-26 08:35:53 +0000312 Value *Ptr = getRandomPointerValue();
313 Value *V = new LoadInst(Ptr, "L", BB->getTerminator());
314 PT->push_back(V);
315 }
316};
317
318struct StoreModifier: public Modifier {
319 StoreModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
Craig Toppere56917c2014-03-08 08:27:28 +0000320 void Act() override {
Alp Tokerf907b892013-12-05 05:44:44 +0000321 // Try to use predefined pointers. If non-exist, use undef pointer value;
Nadav Rotem78bda892012-02-26 08:35:53 +0000322 Value *Ptr = getRandomPointerValue();
323 Type *Tp = Ptr->getType();
324 Value *Val = getRandomValue(Tp->getContainedType(0));
Nadav Rotem63ff91d2012-02-26 12:00:22 +0000325 Type *ValTy = Val->getType();
Nadav Rotem78bda892012-02-26 08:35:53 +0000326
327 // Do not store vectors of i1s because they are unsupported
Nadav Rotem115ec822012-02-26 12:34:17 +0000328 // by the codegen.
329 if (ValTy->isVectorTy() && ValTy->getScalarSizeInBits() == 1)
Nadav Rotem78bda892012-02-26 08:35:53 +0000330 return;
331
332 new StoreInst(Val, Ptr, BB->getTerminator());
333 }
334};
335
336struct BinModifier: public Modifier {
337 BinModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
338
Craig Toppere56917c2014-03-08 08:27:28 +0000339 void Act() override {
Nadav Rotem78bda892012-02-26 08:35:53 +0000340 Value *Val0 = getRandomVal();
341 Value *Val1 = getRandomValue(Val0->getType());
342
343 // Don't handle pointer types.
344 if (Val0->getType()->isPointerTy() ||
345 Val1->getType()->isPointerTy())
346 return;
347
348 // Don't handle i1 types.
349 if (Val0->getType()->getScalarSizeInBits() == 1)
350 return;
351
352
353 bool isFloat = Val0->getType()->getScalarType()->isFloatingPointTy();
354 Instruction* Term = BB->getTerminator();
355 unsigned R = Ran->Rand() % (isFloat ? 7 : 13);
356 Instruction::BinaryOps Op;
357
358 switch (R) {
359 default: llvm_unreachable("Invalid BinOp");
360 case 0:{Op = (isFloat?Instruction::FAdd : Instruction::Add); break; }
361 case 1:{Op = (isFloat?Instruction::FSub : Instruction::Sub); break; }
362 case 2:{Op = (isFloat?Instruction::FMul : Instruction::Mul); break; }
363 case 3:{Op = (isFloat?Instruction::FDiv : Instruction::SDiv); break; }
364 case 4:{Op = (isFloat?Instruction::FDiv : Instruction::UDiv); break; }
365 case 5:{Op = (isFloat?Instruction::FRem : Instruction::SRem); break; }
366 case 6:{Op = (isFloat?Instruction::FRem : Instruction::URem); break; }
367 case 7: {Op = Instruction::Shl; break; }
368 case 8: {Op = Instruction::LShr; break; }
369 case 9: {Op = Instruction::AShr; break; }
370 case 10:{Op = Instruction::And; break; }
371 case 11:{Op = Instruction::Or; break; }
372 case 12:{Op = Instruction::Xor; break; }
373 }
374
375 PT->push_back(BinaryOperator::Create(Op, Val0, Val1, "B", Term));
376 }
377};
378
379/// Generate constant values.
380struct ConstModifier: public Modifier {
381 ConstModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
Craig Toppere56917c2014-03-08 08:27:28 +0000382 void Act() override {
Nadav Rotem78bda892012-02-26 08:35:53 +0000383 Type *Ty = pickType();
384
385 if (Ty->isVectorTy()) {
386 switch (Ran->Rand() % 2) {
387 case 0: if (Ty->getScalarType()->isIntegerTy())
388 return PT->push_back(ConstantVector::getAllOnesValue(Ty));
Galina Kistanovab6448142017-06-10 18:26:19 +0000389 break;
Nadav Rotem78bda892012-02-26 08:35:53 +0000390 case 1: if (Ty->getScalarType()->isIntegerTy())
391 return PT->push_back(ConstantVector::getNullValue(Ty));
392 }
393 }
394
395 if (Ty->isFloatingPointTy()) {
Dylan Noblesmith68f310d2012-04-10 22:44:51 +0000396 // Generate 128 random bits, the size of the (currently)
397 // largest floating-point types.
398 uint64_t RandomBits[2];
399 for (unsigned i = 0; i < 2; ++i)
400 RandomBits[i] = Ran->Rand64();
401
402 APInt RandomInt(Ty->getPrimitiveSizeInBits(), makeArrayRef(RandomBits));
Tim Northover98d9b7e2013-01-22 10:18:26 +0000403 APFloat RandomFloat(Ty->getFltSemantics(), RandomInt);
Dylan Noblesmith68f310d2012-04-10 22:44:51 +0000404
Nadav Rotem78bda892012-02-26 08:35:53 +0000405 if (Ran->Rand() & 1)
406 return PT->push_back(ConstantFP::getNullValue(Ty));
Dylan Noblesmith68f310d2012-04-10 22:44:51 +0000407 return PT->push_back(ConstantFP::get(Ty->getContext(), RandomFloat));
Nadav Rotem78bda892012-02-26 08:35:53 +0000408 }
409
410 if (Ty->isIntegerTy()) {
411 switch (Ran->Rand() % 7) {
David Blaikie30b2c6b2017-06-12 20:09:53 +0000412 case 0:
413 return PT->push_back(ConstantInt::get(
414 Ty, APInt::getAllOnesValue(Ty->getPrimitiveSizeInBits())));
415 case 1:
416 return PT->push_back(ConstantInt::get(
417 Ty, APInt::getNullValue(Ty->getPrimitiveSizeInBits())));
David Blaikie8f9621a2017-06-21 15:20:46 +0000418 case 2:
419 case 3:
420 case 4:
421 case 5:
David Blaikie30b2c6b2017-06-12 20:09:53 +0000422 case 6:
423 PT->push_back(ConstantInt::get(Ty, Ran->Rand()));
Nadav Rotem78bda892012-02-26 08:35:53 +0000424 }
425 }
Nadav Rotem78bda892012-02-26 08:35:53 +0000426 }
427};
428
429struct AllocaModifier: public Modifier {
430 AllocaModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R){}
431
Craig Toppere56917c2014-03-08 08:27:28 +0000432 void Act() override {
Nadav Rotem78bda892012-02-26 08:35:53 +0000433 Type *Tp = pickType();
Matt Arsenault3c1fc762017-04-10 22:27:50 +0000434 const DataLayout &DL = BB->getModule()->getDataLayout();
435 PT->push_back(new AllocaInst(Tp, DL.getAllocaAddrSpace(),
436 "A", BB->getFirstNonPHI()));
Nadav Rotem78bda892012-02-26 08:35:53 +0000437 }
438};
439
440struct ExtractElementModifier: public Modifier {
441 ExtractElementModifier(BasicBlock *BB, PieceTable *PT, Random *R):
442 Modifier(BB, PT, R) {}
443
Craig Toppere56917c2014-03-08 08:27:28 +0000444 void Act() override {
Nadav Rotem78bda892012-02-26 08:35:53 +0000445 Value *Val0 = getRandomVectorValue();
446 Value *V = ExtractElementInst::Create(Val0,
447 ConstantInt::get(Type::getInt32Ty(BB->getContext()),
Nadav Rotemaeacc172012-04-15 20:17:14 +0000448 Ran->Rand() % cast<VectorType>(Val0->getType())->getNumElements()),
Nadav Rotem78bda892012-02-26 08:35:53 +0000449 "E", BB->getTerminator());
450 return PT->push_back(V);
451 }
452};
453
454struct ShuffModifier: public Modifier {
455 ShuffModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
Craig Toppere56917c2014-03-08 08:27:28 +0000456 void Act() override {
Nadav Rotem78bda892012-02-26 08:35:53 +0000457
458 Value *Val0 = getRandomVectorValue();
459 Value *Val1 = getRandomValue(Val0->getType());
460
461 unsigned Width = cast<VectorType>(Val0->getType())->getNumElements();
462 std::vector<Constant*> Idxs;
463
464 Type *I32 = Type::getInt32Ty(BB->getContext());
465 for (unsigned i=0; i<Width; ++i) {
466 Constant *CI = ConstantInt::get(I32, Ran->Rand() % (Width*2));
467 // Pick some undef values.
468 if (!(Ran->Rand() % 5))
469 CI = UndefValue::get(I32);
470 Idxs.push_back(CI);
471 }
472
473 Constant *Mask = ConstantVector::get(Idxs);
474
475 Value *V = new ShuffleVectorInst(Val0, Val1, Mask, "Shuff",
476 BB->getTerminator());
477 PT->push_back(V);
478 }
479};
480
481struct InsertElementModifier: public Modifier {
482 InsertElementModifier(BasicBlock *BB, PieceTable *PT, Random *R):
483 Modifier(BB, PT, R) {}
484
Craig Toppere56917c2014-03-08 08:27:28 +0000485 void Act() override {
Nadav Rotem78bda892012-02-26 08:35:53 +0000486 Value *Val0 = getRandomVectorValue();
487 Value *Val1 = getRandomValue(Val0->getType()->getScalarType());
488
489 Value *V = InsertElementInst::Create(Val0, Val1,
490 ConstantInt::get(Type::getInt32Ty(BB->getContext()),
491 Ran->Rand() % cast<VectorType>(Val0->getType())->getNumElements()),
492 "I", BB->getTerminator());
493 return PT->push_back(V);
494 }
495
496};
497
498struct CastModifier: public Modifier {
499 CastModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
Craig Toppere56917c2014-03-08 08:27:28 +0000500 void Act() override {
Nadav Rotem78bda892012-02-26 08:35:53 +0000501
502 Value *V = getRandomVal();
503 Type *VTy = V->getType();
504 Type *DestTy = pickScalarType();
505
506 // Handle vector casts vectors.
507 if (VTy->isVectorTy()) {
508 VectorType *VecTy = cast<VectorType>(VTy);
509 DestTy = pickVectorType(VecTy->getNumElements());
510 }
511
Nadav Rotemaeacc172012-04-15 20:17:14 +0000512 // no need to cast.
Nadav Rotem78bda892012-02-26 08:35:53 +0000513 if (VTy == DestTy) return;
514
515 // Pointers:
516 if (VTy->isPointerTy()) {
517 if (!DestTy->isPointerTy())
518 DestTy = PointerType::get(DestTy, 0);
519 return PT->push_back(
520 new BitCastInst(V, DestTy, "PC", BB->getTerminator()));
521 }
522
Nadav Rotemaeacc172012-04-15 20:17:14 +0000523 unsigned VSize = VTy->getScalarType()->getPrimitiveSizeInBits();
524 unsigned DestSize = DestTy->getScalarType()->getPrimitiveSizeInBits();
525
Nadav Rotem78bda892012-02-26 08:35:53 +0000526 // Generate lots of bitcasts.
Nadav Rotemaeacc172012-04-15 20:17:14 +0000527 if ((Ran->Rand() & 1) && VSize == DestSize) {
Nadav Rotem78bda892012-02-26 08:35:53 +0000528 return PT->push_back(
529 new BitCastInst(V, DestTy, "BC", BB->getTerminator()));
530 }
531
532 // Both types are integers:
533 if (VTy->getScalarType()->isIntegerTy() &&
534 DestTy->getScalarType()->isIntegerTy()) {
Nadav Rotemaeacc172012-04-15 20:17:14 +0000535 if (VSize > DestSize) {
Nadav Rotem78bda892012-02-26 08:35:53 +0000536 return PT->push_back(
537 new TruncInst(V, DestTy, "Tr", BB->getTerminator()));
538 } else {
Nadav Rotemaeacc172012-04-15 20:17:14 +0000539 assert(VSize < DestSize && "Different int types with the same size?");
Nadav Rotem78bda892012-02-26 08:35:53 +0000540 if (Ran->Rand() & 1)
541 return PT->push_back(
542 new ZExtInst(V, DestTy, "ZE", BB->getTerminator()));
543 return PT->push_back(new SExtInst(V, DestTy, "Se", BB->getTerminator()));
544 }
545 }
546
547 // Fp to int.
548 if (VTy->getScalarType()->isFloatingPointTy() &&
549 DestTy->getScalarType()->isIntegerTy()) {
550 if (Ran->Rand() & 1)
551 return PT->push_back(
552 new FPToSIInst(V, DestTy, "FC", BB->getTerminator()));
553 return PT->push_back(new FPToUIInst(V, DestTy, "FC", BB->getTerminator()));
554 }
555
556 // Int to fp.
557 if (VTy->getScalarType()->isIntegerTy() &&
558 DestTy->getScalarType()->isFloatingPointTy()) {
559 if (Ran->Rand() & 1)
560 return PT->push_back(
561 new SIToFPInst(V, DestTy, "FC", BB->getTerminator()));
562 return PT->push_back(new UIToFPInst(V, DestTy, "FC", BB->getTerminator()));
563
564 }
565
566 // Both floats.
567 if (VTy->getScalarType()->isFloatingPointTy() &&
568 DestTy->getScalarType()->isFloatingPointTy()) {
Nadav Rotemaeacc172012-04-15 20:17:14 +0000569 if (VSize > DestSize) {
Nadav Rotem78bda892012-02-26 08:35:53 +0000570 return PT->push_back(
571 new FPTruncInst(V, DestTy, "Tr", BB->getTerminator()));
Nadav Rotemaeacc172012-04-15 20:17:14 +0000572 } else if (VSize < DestSize) {
Nadav Rotem78bda892012-02-26 08:35:53 +0000573 return PT->push_back(
574 new FPExtInst(V, DestTy, "ZE", BB->getTerminator()));
575 }
Nadav Rotemaeacc172012-04-15 20:17:14 +0000576 // If VSize == DestSize, then the two types must be fp128 and ppc_fp128,
577 // for which there is no defined conversion. So do nothing.
Nadav Rotem78bda892012-02-26 08:35:53 +0000578 }
579 }
580
581};
582
583struct SelectModifier: public Modifier {
584 SelectModifier(BasicBlock *BB, PieceTable *PT, Random *R):
585 Modifier(BB, PT, R) {}
586
Craig Toppere56917c2014-03-08 08:27:28 +0000587 void Act() override {
Nadav Rotem78bda892012-02-26 08:35:53 +0000588 // Try a bunch of different select configuration until a valid one is found.
589 Value *Val0 = getRandomVal();
590 Value *Val1 = getRandomValue(Val0->getType());
591
592 Type *CondTy = Type::getInt1Ty(Context);
593
594 // If the value type is a vector, and we allow vector select, then in 50%
595 // of the cases generate a vector select.
596 if (Val0->getType()->isVectorTy() && (Ran->Rand() % 1)) {
597 unsigned NumElem = cast<VectorType>(Val0->getType())->getNumElements();
598 CondTy = VectorType::get(CondTy, NumElem);
599 }
600
601 Value *Cond = getRandomValue(CondTy);
602 Value *V = SelectInst::Create(Cond, Val0, Val1, "Sl", BB->getTerminator());
603 return PT->push_back(V);
604 }
605};
606
607
608struct CmpModifier: public Modifier {
609 CmpModifier(BasicBlock *BB, PieceTable *PT, Random *R):Modifier(BB, PT, R) {}
Craig Toppere56917c2014-03-08 08:27:28 +0000610 void Act() override {
Nadav Rotem78bda892012-02-26 08:35:53 +0000611
612 Value *Val0 = getRandomVal();
613 Value *Val1 = getRandomValue(Val0->getType());
614
615 if (Val0->getType()->isPointerTy()) return;
616 bool fp = Val0->getType()->getScalarType()->isFloatingPointTy();
617
618 int op;
619 if (fp) {
620 op = Ran->Rand() %
621 (CmpInst::LAST_FCMP_PREDICATE - CmpInst::FIRST_FCMP_PREDICATE) +
622 CmpInst::FIRST_FCMP_PREDICATE;
623 } else {
624 op = Ran->Rand() %
625 (CmpInst::LAST_ICMP_PREDICATE - CmpInst::FIRST_ICMP_PREDICATE) +
626 CmpInst::FIRST_ICMP_PREDICATE;
627 }
628
629 Value *V = CmpInst::Create(fp ? Instruction::FCmp : Instruction::ICmp,
Craig Topper1c3f2832015-12-15 06:11:33 +0000630 (CmpInst::Predicate)op, Val0, Val1, "Cmp",
631 BB->getTerminator());
Nadav Rotem78bda892012-02-26 08:35:53 +0000632 return PT->push_back(V);
633 }
634};
635
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000636} // end anonymous namespace
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +0000637
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000638static void FillFunction(Function *F, Random &R) {
Nadav Rotem78bda892012-02-26 08:35:53 +0000639 // Create a legal entry block.
640 BasicBlock *BB = BasicBlock::Create(F->getContext(), "BB", F);
641 ReturnInst::Create(F->getContext(), BB);
642
643 // Create the value table.
644 Modifier::PieceTable PT;
Nadav Rotem78bda892012-02-26 08:35:53 +0000645
646 // Consider arguments as legal values.
Pawel Bylica23663472015-06-24 11:49:44 +0000647 for (auto &arg : F->args())
648 PT.push_back(&arg);
Nadav Rotem78bda892012-02-26 08:35:53 +0000649
650 // List of modifiers which add new random instructions.
Pawel Bylica23663472015-06-24 11:49:44 +0000651 std::vector<std::unique_ptr<Modifier>> Modifiers;
652 Modifiers.emplace_back(new LoadModifier(BB, &PT, &R));
653 Modifiers.emplace_back(new StoreModifier(BB, &PT, &R));
654 auto SM = Modifiers.back().get();
655 Modifiers.emplace_back(new ExtractElementModifier(BB, &PT, &R));
656 Modifiers.emplace_back(new ShuffModifier(BB, &PT, &R));
657 Modifiers.emplace_back(new InsertElementModifier(BB, &PT, &R));
658 Modifiers.emplace_back(new BinModifier(BB, &PT, &R));
659 Modifiers.emplace_back(new CastModifier(BB, &PT, &R));
660 Modifiers.emplace_back(new SelectModifier(BB, &PT, &R));
661 Modifiers.emplace_back(new CmpModifier(BB, &PT, &R));
Nadav Rotem78bda892012-02-26 08:35:53 +0000662
663 // Generate the random instructions
Pawel Bylica23663472015-06-24 11:49:44 +0000664 AllocaModifier{BB, &PT, &R}.ActN(5); // Throw in a few allocas
665 ConstModifier{BB, &PT, &R}.ActN(40); // Throw in a few constants
Nadav Rotem78bda892012-02-26 08:35:53 +0000666
Pawel Bylica23663472015-06-24 11:49:44 +0000667 for (unsigned i = 0; i < SizeCL / Modifiers.size(); ++i)
668 for (auto &Mod : Modifiers)
669 Mod->Act();
Nadav Rotem78bda892012-02-26 08:35:53 +0000670
671 SM->ActN(5); // Throw in a few stores.
672}
673
Juergen Ributzka05c5a932013-11-19 03:08:35 +0000674static void IntroduceControlFlow(Function *F, Random &R) {
Nadav Rotem0fb74082012-06-21 08:58:15 +0000675 std::vector<Instruction*> BoolInst;
Pawel Bylica23663472015-06-24 11:49:44 +0000676 for (auto &Instr : F->front()) {
677 if (Instr.getType() == IntegerType::getInt1Ty(F->getContext()))
678 BoolInst.push_back(&Instr);
Nadav Rotem78bda892012-02-26 08:35:53 +0000679 }
680
Marshall Clowe9110d72017-02-16 14:37:03 +0000681 std::shuffle(BoolInst.begin(), BoolInst.end(), R);
Nadav Rotem0fb74082012-06-21 08:58:15 +0000682
Pawel Bylica23663472015-06-24 11:49:44 +0000683 for (auto *Instr : BoolInst) {
Nadav Rotem78bda892012-02-26 08:35:53 +0000684 BasicBlock *Curr = Instr->getParent();
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +0000685 BasicBlock::iterator Loc = Instr->getIterator();
Nadav Rotem78bda892012-02-26 08:35:53 +0000686 BasicBlock *Next = Curr->splitBasicBlock(Loc, "CF");
687 Instr->moveBefore(Curr->getTerminator());
688 if (Curr != &F->getEntryBlock()) {
689 BranchInst::Create(Curr, Next, Instr, Curr->getTerminator());
690 Curr->getTerminator()->eraseFromParent();
691 }
692 }
693}
694
Pawel Bylicaedb02102015-07-10 10:01:47 +0000695}
696
Nadav Rotem78bda892012-02-26 08:35:53 +0000697int main(int argc, char **argv) {
Pawel Bylicaedb02102015-07-10 10:01:47 +0000698 using namespace llvm;
699
Nadav Rotem78bda892012-02-26 08:35:53 +0000700 // Init LLVM, call llvm_shutdown() on exit, parse args, etc.
Pawel Bylica4dd430f2015-07-13 11:25:56 +0000701 PrettyStackTraceProgram X(argc, argv);
Nadav Rotem78bda892012-02-26 08:35:53 +0000702 cl::ParseCommandLineOptions(argc, argv, "llvm codegen stress-tester\n");
703 llvm_shutdown_obj Y;
704
Mehdi Amini03b42e42016-04-14 21:59:01 +0000705 auto M = make_unique<Module>("/tmp/autogen.bc", Context);
Nadav Rotem78bda892012-02-26 08:35:53 +0000706 Function *F = GenEmptyFunction(M.get());
Nadav Rotem0fb74082012-06-21 08:58:15 +0000707
708 // Pick an initial seed value
709 Random R(SeedCL);
710 // Generate lots of random instructions inside a single basic block.
711 FillFunction(F, R);
712 // Break the basic block into many loops.
713 IntroduceControlFlow(F, R);
Nadav Rotem78bda892012-02-26 08:35:53 +0000714
715 // Figure out what stream we are supposed to write to...
Ahmed Charles56440fd2014-03-06 05:51:42 +0000716 std::unique_ptr<tool_output_file> Out;
Nadav Rotem78bda892012-02-26 08:35:53 +0000717 // Default to standard output.
718 if (OutputFilename.empty())
719 OutputFilename = "-";
720
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000721 std::error_code EC;
722 Out.reset(new tool_output_file(OutputFilename, EC, sys::fs::F_None));
723 if (EC) {
724 errs() << EC.message() << '\n';
Nadav Rotem78bda892012-02-26 08:35:53 +0000725 return 1;
726 }
727
Chandler Carruth30d69c22015-02-13 10:01:29 +0000728 legacy::PassManager Passes;
Nadav Rotem78bda892012-02-26 08:35:53 +0000729 Passes.add(createVerifierPass());
Chandler Carruth3bdf0432014-01-12 11:39:04 +0000730 Passes.add(createPrintModulePass(Out->os()));
Nadav Rotem78bda892012-02-26 08:35:53 +0000731 Passes.run(*M.get());
Nadav Rotem78bda892012-02-26 08:35:53 +0000732 Out->keep();
733
734 return 0;
735}