[OptTable] Fix typo VALUE => VALUES (NFCI) (#121523)
[llvm-project.git] / llvm / tools / llvm-stress / llvm-stress.cpp
blobe44b6023fff231ea5b7d8406071ae9474aa76a04
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.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/APFloat.h"
15 #include "llvm/ADT/APInt.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/Twine.h"
20 #include "llvm/IR/BasicBlock.h"
21 #include "llvm/IR/CallingConv.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/IR/GlobalValue.h"
27 #include "llvm/IR/InstrTypes.h"
28 #include "llvm/IR/Instruction.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/Type.h"
33 #include "llvm/IR/Value.h"
34 #include "llvm/IR/Verifier.h"
35 #include "llvm/Support/Casting.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/FileSystem.h"
39 #include "llvm/Support/InitLLVM.h"
40 #include "llvm/Support/ToolOutputFile.h"
41 #include "llvm/Support/WithColor.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include <algorithm>
44 #include <cassert>
45 #include <cstddef>
46 #include <cstdint>
47 #include <memory>
48 #include <string>
49 #include <system_error>
50 #include <vector>
52 namespace llvm {
54 static cl::OptionCategory StressCategory("Stress Options");
56 static cl::opt<unsigned> SeedCL("seed", cl::desc("Seed used for randomness"),
57 cl::init(0), cl::cat(StressCategory));
59 static cl::opt<unsigned> SizeCL(
60 "size",
61 cl::desc("The estimated size of the generated function (# of instrs)"),
62 cl::init(100), cl::cat(StressCategory));
64 static cl::opt<std::string> OutputFilename("o",
65 cl::desc("Override output filename"),
66 cl::value_desc("filename"),
67 cl::cat(StressCategory));
69 static cl::list<StringRef> AdditionalScalarTypes(
70 "types", cl::CommaSeparated,
71 cl::desc("Additional IR scalar types "
72 "(always includes i1, i8, i16, i32, i64, float and double)"));
74 static cl::opt<bool> EnableScalableVectors(
75 "enable-scalable-vectors",
76 cl::desc("Generate IR involving scalable vector types"),
77 cl::init(false), cl::cat(StressCategory));
80 namespace {
82 /// A utility class to provide a pseudo-random number generator which is
83 /// the same across all platforms. This is somewhat close to the libc
84 /// implementation. Note: This is not a cryptographically secure pseudorandom
85 /// number generator.
86 class Random {
87 public:
88 /// C'tor
89 Random(unsigned _seed):Seed(_seed) {}
91 /// Return a random integer, up to a
92 /// maximum of 2**19 - 1.
93 uint32_t Rand() {
94 uint32_t Val = Seed + 0x000b07a1;
95 Seed = (Val * 0x3c7c0ac1);
96 // Only lowest 19 bits are random-ish.
97 return Seed & 0x7ffff;
100 /// Return a random 64 bit integer.
101 uint64_t Rand64() {
102 uint64_t Val = Rand() & 0xffff;
103 Val |= uint64_t(Rand() & 0xffff) << 16;
104 Val |= uint64_t(Rand() & 0xffff) << 32;
105 Val |= uint64_t(Rand() & 0xffff) << 48;
106 return Val;
109 /// Rand operator for STL algorithms.
110 ptrdiff_t operator()(ptrdiff_t y) {
111 return Rand64() % y;
114 /// Make this like a C++11 random device
115 using result_type = uint32_t ;
117 static constexpr result_type min() { return 0; }
118 static constexpr result_type max() { return 0x7ffff; }
120 uint32_t operator()() {
121 uint32_t Val = Rand();
122 assert(Val <= max() && "Random value out of range");
123 return Val;
126 private:
127 unsigned Seed;
130 /// Generate an empty function with a default argument list.
131 Function *GenEmptyFunction(Module *M) {
132 // Define a few arguments
133 LLVMContext &Context = M->getContext();
134 Type* ArgsTy[] = {
135 PointerType::get(Context, 0),
136 PointerType::get(Context, 0),
137 PointerType::get(Context, 0),
138 Type::getInt32Ty(Context),
139 Type::getInt64Ty(Context),
140 Type::getInt8Ty(Context)
143 auto *FuncTy = FunctionType::get(Type::getVoidTy(Context), ArgsTy, false);
144 // Pick a unique name to describe the input parameters
145 Twine Name = "autogen_SD" + Twine{SeedCL};
146 auto *Func = Function::Create(FuncTy, GlobalValue::ExternalLinkage, Name, M);
147 Func->setCallingConv(CallingConv::C);
148 return Func;
151 /// A base class, implementing utilities needed for
152 /// modifying and adding new random instructions.
153 struct Modifier {
154 /// Used to store the randomly generated values.
155 using PieceTable = std::vector<Value *>;
157 public:
158 /// C'tor
159 Modifier(BasicBlock *Block, PieceTable *PT, Random *R)
160 : BB(Block), PT(PT), Ran(R), Context(BB->getContext()) {
161 ScalarTypes.assign({Type::getInt1Ty(Context), Type::getInt8Ty(Context),
162 Type::getInt16Ty(Context), Type::getInt32Ty(Context),
163 Type::getInt64Ty(Context), Type::getFloatTy(Context),
164 Type::getDoubleTy(Context)});
166 for (auto &Arg : AdditionalScalarTypes) {
167 Type *Ty = nullptr;
168 if (Arg == "half")
169 Ty = Type::getHalfTy(Context);
170 else if (Arg == "fp128")
171 Ty = Type::getFP128Ty(Context);
172 else if (Arg == "x86_fp80")
173 Ty = Type::getX86_FP80Ty(Context);
174 else if (Arg == "ppc_fp128")
175 Ty = Type::getPPC_FP128Ty(Context);
176 else if (Arg.starts_with("i")) {
177 unsigned N = 0;
178 Arg.drop_front().getAsInteger(10, N);
179 if (N > 0)
180 Ty = Type::getIntNTy(Context, N);
182 if (!Ty) {
183 errs() << "Invalid IR scalar type: '" << Arg << "'!\n";
184 exit(1);
187 ScalarTypes.push_back(Ty);
191 /// virtual D'tor to silence warnings.
192 virtual ~Modifier() = default;
194 /// Add a new instruction.
195 virtual void Act() = 0;
197 /// Add N new instructions,
198 virtual void ActN(unsigned n) {
199 for (unsigned i=0; i<n; ++i)
200 Act();
203 protected:
204 /// Return a random integer.
205 uint32_t getRandom() {
206 return Ran->Rand();
209 /// Return a random value from the list of known values.
210 Value *getRandomVal() {
211 assert(PT->size());
212 return PT->at(getRandom() % PT->size());
215 Constant *getRandomConstant(Type *Tp) {
216 if (Tp->isIntegerTy()) {
217 if (getRandom() & 1)
218 return ConstantInt::getAllOnesValue(Tp);
219 return ConstantInt::getNullValue(Tp);
220 } else if (Tp->isFloatingPointTy()) {
221 if (getRandom() & 1)
222 return ConstantFP::getAllOnesValue(Tp);
223 return ConstantFP::getZero(Tp);
225 return UndefValue::get(Tp);
228 /// Return a random value with a known type.
229 Value *getRandomValue(Type *Tp) {
230 unsigned index = getRandom();
231 for (unsigned i=0; i<PT->size(); ++i) {
232 Value *V = PT->at((index + i) % PT->size());
233 if (V->getType() == Tp)
234 return V;
237 // If the requested type was not found, generate a constant value.
238 if (Tp->isIntegerTy()) {
239 if (getRandom() & 1)
240 return ConstantInt::getAllOnesValue(Tp);
241 return ConstantInt::getNullValue(Tp);
242 } else if (Tp->isFloatingPointTy()) {
243 if (getRandom() & 1)
244 return ConstantFP::getAllOnesValue(Tp);
245 return ConstantFP::getZero(Tp);
246 } else if (auto *VTp = dyn_cast<FixedVectorType>(Tp)) {
247 std::vector<Constant*> TempValues;
248 TempValues.reserve(VTp->getNumElements());
249 for (unsigned i = 0; i < VTp->getNumElements(); ++i)
250 TempValues.push_back(getRandomConstant(VTp->getScalarType()));
252 ArrayRef<Constant*> VectorValue(TempValues);
253 return ConstantVector::get(VectorValue);
256 return UndefValue::get(Tp);
259 /// Return a random value of any pointer type.
260 Value *getRandomPointerValue() {
261 unsigned index = getRandom();
262 for (unsigned i=0; i<PT->size(); ++i) {
263 Value *V = PT->at((index + i) % PT->size());
264 if (V->getType()->isPointerTy())
265 return V;
267 return UndefValue::get(pickPointerType());
270 /// Return a random value of any vector type.
271 Value *getRandomVectorValue() {
272 unsigned index = getRandom();
273 for (unsigned i=0; i<PT->size(); ++i) {
274 Value *V = PT->at((index + i) % PT->size());
275 if (V->getType()->isVectorTy())
276 return V;
278 return UndefValue::get(pickVectorType());
281 /// Pick a random type.
282 Type *pickType() {
283 return (getRandom() & 1) ? pickVectorType() : pickScalarType();
286 /// Pick a random pointer type.
287 Type *pickPointerType() {
288 Type *Ty = pickType();
289 return PointerType::get(Ty, 0);
292 /// Pick a random vector type.
293 Type *pickVectorType(VectorType *VTy = nullptr) {
295 Type *Ty = pickScalarType();
297 if (VTy)
298 return VectorType::get(Ty, VTy->getElementCount());
300 // Select either fixed length or scalable vectors with 50% probability
301 // (only if scalable vectors are enabled)
302 bool Scalable = EnableScalableVectors && getRandom() & 1;
304 // Pick a random vector width in the range 2**0 to 2**4.
305 // by adding two randoms we are generating a normal-like distribution
306 // around 2**3.
307 unsigned width = 1<<((getRandom() % 3) + (getRandom() % 3));
308 return VectorType::get(Ty, width, Scalable);
311 /// Pick a random scalar type.
312 Type *pickScalarType() {
313 return ScalarTypes[getRandom() % ScalarTypes.size()];
316 /// Basic block to populate
317 BasicBlock *BB;
319 /// Value table
320 PieceTable *PT;
322 /// Random number generator
323 Random *Ran;
325 /// Context
326 LLVMContext &Context;
328 std::vector<Type *> ScalarTypes;
331 struct LoadModifier: public Modifier {
332 LoadModifier(BasicBlock *BB, PieceTable *PT, Random *R)
333 : Modifier(BB, PT, R) {}
335 void Act() override {
336 // Try to use predefined pointers. If non-exist, use undef pointer value;
337 Value *Ptr = getRandomPointerValue();
338 Type *Ty = pickType();
339 Value *V = new LoadInst(Ty, Ptr, "L", BB->getTerminator()->getIterator());
340 PT->push_back(V);
344 struct StoreModifier: public Modifier {
345 StoreModifier(BasicBlock *BB, PieceTable *PT, Random *R)
346 : Modifier(BB, PT, R) {}
348 void Act() override {
349 // Try to use predefined pointers. If non-exist, use undef pointer value;
350 Value *Ptr = getRandomPointerValue();
351 Type *ValTy = pickType();
353 // Do not store vectors of i1s because they are unsupported
354 // by the codegen.
355 if (ValTy->isVectorTy() && ValTy->getScalarSizeInBits() == 1)
356 return;
358 Value *Val = getRandomValue(ValTy);
359 new StoreInst(Val, Ptr, BB->getTerminator()->getIterator());
363 struct BinModifier: public Modifier {
364 BinModifier(BasicBlock *BB, PieceTable *PT, Random *R)
365 : Modifier(BB, PT, R) {}
367 void Act() override {
368 Value *Val0 = getRandomVal();
369 Value *Val1 = getRandomValue(Val0->getType());
371 // Don't handle pointer types.
372 if (Val0->getType()->isPointerTy() ||
373 Val1->getType()->isPointerTy())
374 return;
376 // Don't handle i1 types.
377 if (Val0->getType()->getScalarSizeInBits() == 1)
378 return;
380 bool isFloat = Val0->getType()->getScalarType()->isFloatingPointTy();
381 Instruction* Term = BB->getTerminator();
382 unsigned R = getRandom() % (isFloat ? 7 : 13);
383 Instruction::BinaryOps Op;
385 switch (R) {
386 default: llvm_unreachable("Invalid BinOp");
387 case 0:{Op = (isFloat?Instruction::FAdd : Instruction::Add); break; }
388 case 1:{Op = (isFloat?Instruction::FSub : Instruction::Sub); break; }
389 case 2:{Op = (isFloat?Instruction::FMul : Instruction::Mul); break; }
390 case 3:{Op = (isFloat?Instruction::FDiv : Instruction::SDiv); break; }
391 case 4:{Op = (isFloat?Instruction::FDiv : Instruction::UDiv); break; }
392 case 5:{Op = (isFloat?Instruction::FRem : Instruction::SRem); break; }
393 case 6:{Op = (isFloat?Instruction::FRem : Instruction::URem); break; }
394 case 7: {Op = Instruction::Shl; break; }
395 case 8: {Op = Instruction::LShr; break; }
396 case 9: {Op = Instruction::AShr; break; }
397 case 10:{Op = Instruction::And; break; }
398 case 11:{Op = Instruction::Or; break; }
399 case 12:{Op = Instruction::Xor; break; }
402 PT->push_back(
403 BinaryOperator::Create(Op, Val0, Val1, "B", Term->getIterator()));
407 /// Generate constant values.
408 struct ConstModifier: public Modifier {
409 ConstModifier(BasicBlock *BB, PieceTable *PT, Random *R)
410 : Modifier(BB, PT, R) {}
412 void Act() override {
413 Type *Ty = pickType();
415 if (Ty->isVectorTy()) {
416 switch (getRandom() % 2) {
417 case 0: if (Ty->isIntOrIntVectorTy())
418 return PT->push_back(ConstantVector::getAllOnesValue(Ty));
419 break;
420 case 1: if (Ty->isIntOrIntVectorTy())
421 return PT->push_back(ConstantVector::getNullValue(Ty));
425 if (Ty->isFloatingPointTy()) {
426 // Generate 128 random bits, the size of the (currently)
427 // largest floating-point types.
428 uint64_t RandomBits[2];
429 for (unsigned i = 0; i < 2; ++i)
430 RandomBits[i] = Ran->Rand64();
432 APInt RandomInt(Ty->getPrimitiveSizeInBits(), ArrayRef(RandomBits));
433 APFloat RandomFloat(Ty->getFltSemantics(), RandomInt);
435 if (getRandom() & 1)
436 return PT->push_back(ConstantFP::getZero(Ty));
437 return PT->push_back(ConstantFP::get(Ty->getContext(), RandomFloat));
440 if (Ty->isIntegerTy()) {
441 switch (getRandom() % 7) {
442 case 0:
443 return PT->push_back(ConstantInt::get(
444 Ty, APInt::getAllOnes(Ty->getPrimitiveSizeInBits())));
445 case 1:
446 return PT->push_back(
447 ConstantInt::get(Ty, APInt::getZero(Ty->getPrimitiveSizeInBits())));
448 case 2:
449 case 3:
450 case 4:
451 case 5:
452 case 6:
453 PT->push_back(ConstantInt::get(Ty, getRandom()));
459 struct AllocaModifier: public Modifier {
460 AllocaModifier(BasicBlock *BB, PieceTable *PT, Random *R)
461 : Modifier(BB, PT, R) {}
463 void Act() override {
464 Type *Tp = pickType();
465 const DataLayout &DL = BB->getDataLayout();
466 PT->push_back(new AllocaInst(Tp, DL.getAllocaAddrSpace(), "A",
467 BB->getFirstNonPHIIt()));
471 struct ExtractElementModifier: public Modifier {
472 ExtractElementModifier(BasicBlock *BB, PieceTable *PT, Random *R)
473 : Modifier(BB, PT, R) {}
475 void Act() override {
476 Value *Val0 = getRandomVectorValue();
477 Value *V = ExtractElementInst::Create(
478 Val0, getRandomValue(Type::getInt32Ty(BB->getContext())), "E",
479 BB->getTerminator()->getIterator());
480 return PT->push_back(V);
484 struct ShuffModifier: public Modifier {
485 ShuffModifier(BasicBlock *BB, PieceTable *PT, Random *R)
486 : Modifier(BB, PT, R) {}
488 void Act() override {
489 Value *Val0 = getRandomVectorValue();
490 Value *Val1 = getRandomValue(Val0->getType());
492 // Can't express arbitrary shufflevectors for scalable vectors
493 if (isa<ScalableVectorType>(Val0->getType()))
494 return;
496 unsigned Width = cast<FixedVectorType>(Val0->getType())->getNumElements();
497 std::vector<Constant*> Idxs;
499 Type *I32 = Type::getInt32Ty(BB->getContext());
500 for (unsigned i=0; i<Width; ++i) {
501 Constant *CI = ConstantInt::get(I32, getRandom() % (Width*2));
502 // Pick some undef values.
503 if (!(getRandom() % 5))
504 CI = UndefValue::get(I32);
505 Idxs.push_back(CI);
508 Constant *Mask = ConstantVector::get(Idxs);
510 Value *V = new ShuffleVectorInst(Val0, Val1, Mask, "Shuff",
511 BB->getTerminator()->getIterator());
512 PT->push_back(V);
516 struct InsertElementModifier: public Modifier {
517 InsertElementModifier(BasicBlock *BB, PieceTable *PT, Random *R)
518 : Modifier(BB, PT, R) {}
520 void Act() override {
521 Value *Val0 = getRandomVectorValue();
522 Value *Val1 = getRandomValue(Val0->getType()->getScalarType());
524 Value *V = InsertElementInst::Create(
525 Val0, Val1, getRandomValue(Type::getInt32Ty(BB->getContext())), "I",
526 BB->getTerminator()->getIterator());
527 return PT->push_back(V);
531 struct CastModifier: public Modifier {
532 CastModifier(BasicBlock *BB, PieceTable *PT, Random *R)
533 : Modifier(BB, PT, R) {}
535 void Act() override {
536 Value *V = getRandomVal();
537 Type *VTy = V->getType();
538 Type *DestTy = pickScalarType();
540 // Handle vector casts vectors.
541 if (VTy->isVectorTy())
542 DestTy = pickVectorType(cast<VectorType>(VTy));
544 // no need to cast.
545 if (VTy == DestTy) return;
547 // Pointers:
548 if (VTy->isPointerTy()) {
549 if (!DestTy->isPointerTy())
550 DestTy = PointerType::get(DestTy, 0);
551 return PT->push_back(
552 new BitCastInst(V, DestTy, "PC", BB->getTerminator()->getIterator()));
555 unsigned VSize = VTy->getScalarType()->getPrimitiveSizeInBits();
556 unsigned DestSize = DestTy->getScalarType()->getPrimitiveSizeInBits();
558 // Generate lots of bitcasts.
559 if ((getRandom() & 1) && VSize == DestSize) {
560 return PT->push_back(
561 new BitCastInst(V, DestTy, "BC", BB->getTerminator()->getIterator()));
564 // Both types are integers:
565 if (VTy->isIntOrIntVectorTy() && DestTy->isIntOrIntVectorTy()) {
566 if (VSize > DestSize) {
567 return PT->push_back(
568 new TruncInst(V, DestTy, "Tr", BB->getTerminator()->getIterator()));
569 } else {
570 assert(VSize < DestSize && "Different int types with the same size?");
571 if (getRandom() & 1)
572 return PT->push_back(new ZExtInst(
573 V, DestTy, "ZE", BB->getTerminator()->getIterator()));
574 return PT->push_back(
575 new SExtInst(V, DestTy, "Se", BB->getTerminator()->getIterator()));
579 // Fp to int.
580 if (VTy->isFPOrFPVectorTy() && DestTy->isIntOrIntVectorTy()) {
581 if (getRandom() & 1)
582 return PT->push_back(new FPToSIInst(
583 V, DestTy, "FC", BB->getTerminator()->getIterator()));
584 return PT->push_back(
585 new FPToUIInst(V, DestTy, "FC", BB->getTerminator()->getIterator()));
588 // Int to fp.
589 if (VTy->isIntOrIntVectorTy() && DestTy->isFPOrFPVectorTy()) {
590 if (getRandom() & 1)
591 return PT->push_back(new SIToFPInst(
592 V, DestTy, "FC", BB->getTerminator()->getIterator()));
593 return PT->push_back(
594 new UIToFPInst(V, DestTy, "FC", BB->getTerminator()->getIterator()));
597 // Both floats.
598 if (VTy->isFPOrFPVectorTy() && DestTy->isFPOrFPVectorTy()) {
599 if (VSize > DestSize) {
600 return PT->push_back(new FPTruncInst(
601 V, DestTy, "Tr", BB->getTerminator()->getIterator()));
602 } else if (VSize < DestSize) {
603 return PT->push_back(
604 new FPExtInst(V, DestTy, "ZE", BB->getTerminator()->getIterator()));
606 // If VSize == DestSize, then the two types must be fp128 and ppc_fp128,
607 // for which there is no defined conversion. So do nothing.
612 struct SelectModifier: public Modifier {
613 SelectModifier(BasicBlock *BB, PieceTable *PT, Random *R)
614 : Modifier(BB, PT, R) {}
616 void Act() override {
617 // Try a bunch of different select configuration until a valid one is found.
618 Value *Val0 = getRandomVal();
619 Value *Val1 = getRandomValue(Val0->getType());
621 Type *CondTy = Type::getInt1Ty(Context);
623 // If the value type is a vector, and we allow vector select, then in 50%
624 // of the cases generate a vector select.
625 if (auto *VTy = dyn_cast<VectorType>(Val0->getType()))
626 if (getRandom() & 1)
627 CondTy = VectorType::get(CondTy, VTy->getElementCount());
629 Value *Cond = getRandomValue(CondTy);
630 Value *V = SelectInst::Create(Cond, Val0, Val1, "Sl",
631 BB->getTerminator()->getIterator());
632 return PT->push_back(V);
636 struct CmpModifier: public Modifier {
637 CmpModifier(BasicBlock *BB, PieceTable *PT, Random *R)
638 : Modifier(BB, PT, R) {}
640 void Act() override {
641 Value *Val0 = getRandomVal();
642 Value *Val1 = getRandomValue(Val0->getType());
644 if (Val0->getType()->isPointerTy()) return;
645 bool fp = Val0->getType()->getScalarType()->isFloatingPointTy();
647 int op;
648 if (fp) {
649 op = getRandom() %
650 (CmpInst::LAST_FCMP_PREDICATE - CmpInst::FIRST_FCMP_PREDICATE) +
651 CmpInst::FIRST_FCMP_PREDICATE;
652 } else {
653 op = getRandom() %
654 (CmpInst::LAST_ICMP_PREDICATE - CmpInst::FIRST_ICMP_PREDICATE) +
655 CmpInst::FIRST_ICMP_PREDICATE;
658 Value *V = CmpInst::Create(fp ? Instruction::FCmp : Instruction::ICmp,
659 (CmpInst::Predicate)op, Val0, Val1, "Cmp",
660 BB->getTerminator()->getIterator());
661 return PT->push_back(V);
665 } // end anonymous namespace
667 static void FillFunction(Function *F, Random &R) {
668 // Create a legal entry block.
669 BasicBlock *BB = BasicBlock::Create(F->getContext(), "BB", F);
670 ReturnInst::Create(F->getContext(), BB);
672 // Create the value table.
673 Modifier::PieceTable PT;
675 // Consider arguments as legal values.
676 for (auto &arg : F->args())
677 PT.push_back(&arg);
679 // List of modifiers which add new random instructions.
680 std::vector<std::unique_ptr<Modifier>> Modifiers;
681 Modifiers.emplace_back(new LoadModifier(BB, &PT, &R));
682 Modifiers.emplace_back(new StoreModifier(BB, &PT, &R));
683 auto SM = Modifiers.back().get();
684 Modifiers.emplace_back(new ExtractElementModifier(BB, &PT, &R));
685 Modifiers.emplace_back(new ShuffModifier(BB, &PT, &R));
686 Modifiers.emplace_back(new InsertElementModifier(BB, &PT, &R));
687 Modifiers.emplace_back(new BinModifier(BB, &PT, &R));
688 Modifiers.emplace_back(new CastModifier(BB, &PT, &R));
689 Modifiers.emplace_back(new SelectModifier(BB, &PT, &R));
690 Modifiers.emplace_back(new CmpModifier(BB, &PT, &R));
692 // Generate the random instructions
693 AllocaModifier{BB, &PT, &R}.ActN(5); // Throw in a few allocas
694 ConstModifier{BB, &PT, &R}.ActN(40); // Throw in a few constants
696 for (unsigned i = 0; i < SizeCL / Modifiers.size(); ++i)
697 for (auto &Mod : Modifiers)
698 Mod->Act();
700 SM->ActN(5); // Throw in a few stores.
703 static void IntroduceControlFlow(Function *F, Random &R) {
704 std::vector<Instruction*> BoolInst;
705 for (auto &Instr : F->front()) {
706 if (Instr.getType() == IntegerType::getInt1Ty(F->getContext()))
707 BoolInst.push_back(&Instr);
710 llvm::shuffle(BoolInst.begin(), BoolInst.end(), R);
712 for (auto *Instr : BoolInst) {
713 BasicBlock *Curr = Instr->getParent();
714 BasicBlock::iterator Loc = Instr->getIterator();
715 BasicBlock *Next = Curr->splitBasicBlock(Loc, "CF");
716 Instr->moveBefore(Curr->getTerminator());
717 if (Curr != &F->getEntryBlock()) {
718 BranchInst::Create(Curr, Next, Instr,
719 Curr->getTerminator()->getIterator());
720 Curr->getTerminator()->eraseFromParent();
725 } // end namespace llvm
727 int main(int argc, char **argv) {
728 using namespace llvm;
730 InitLLVM X(argc, argv);
731 cl::HideUnrelatedOptions({&StressCategory, &getColorCategory()});
732 cl::ParseCommandLineOptions(argc, argv, "llvm codegen stress-tester\n");
734 LLVMContext Context;
735 auto M = std::make_unique<Module>("/tmp/autogen.bc", Context);
736 Function *F = GenEmptyFunction(M.get());
738 // Pick an initial seed value
739 Random R(SeedCL);
740 // Generate lots of random instructions inside a single basic block.
741 FillFunction(F, R);
742 // Break the basic block into many loops.
743 IntroduceControlFlow(F, R);
745 // Figure out what stream we are supposed to write to...
746 std::unique_ptr<ToolOutputFile> Out;
747 // Default to standard output.
748 if (OutputFilename.empty())
749 OutputFilename = "-";
751 std::error_code EC;
752 Out.reset(new ToolOutputFile(OutputFilename, EC, sys::fs::OF_None));
753 if (EC) {
754 errs() << EC.message() << '\n';
755 return 1;
758 // Check that the generated module is accepted by the verifier.
759 if (verifyModule(*M.get(), &Out->os()))
760 report_fatal_error("Broken module found, compilation aborted!");
762 // Output textual IR.
763 M->print(Out->os(), nullptr);
765 Out->keep();
767 return 0;