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