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