<commit_before>//===- llvm/unittests/IR/DominatorTreeTest.cpp - Constants unit tests -----===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/IR/Dominators.h"
#include "llvm/Analysis/PostDominators.h"
#include "llvm/AsmParser/Parser.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/Support/SourceMgr.h"
#include "gtest/gtest.h"

using namespace llvm;

namespace llvm {
  void initializeDPassPass(PassRegistry&);

  namespace {
    struct DPass : public FunctionPass {
      static char ID;
      bool runOnFunction(Function &F) override {
        DominatorTree *DT =
            &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
        PostDominatorTree *PDT =
            &getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
        Function::iterator FI = F.begin();

        BasicBlock *BB0 = &*FI++;
        BasicBlock::iterator BBI = BB0->begin();
        Instruction *Y1 = &*BBI++;
        Instruction *Y2 = &*BBI++;
        Instruction *Y3 = &*BBI++;

        BasicBlock *BB1 = &*FI++;
        BBI = BB1->begin();
        Instruction *Y4 = &*BBI++;

        BasicBlock *BB2 = &*FI++;
        BBI = BB2->begin();
        Instruction *Y5 = &*BBI++;

        BasicBlock *BB3 = &*FI++;
        BBI = BB3->begin();
        Instruction *Y6 = &*BBI++;
        Instruction *Y7 = &*BBI++;

        BasicBlock *BB4 = &*FI++;
        BBI = BB4->begin();
        Instruction *Y8 = &*BBI++;
        Instruction *Y9 = &*BBI++;

        // Reachability
        EXPECT_TRUE(DT->isReachableFromEntry(BB0));
        EXPECT_TRUE(DT->isReachableFromEntry(BB1));
        EXPECT_TRUE(DT->isReachableFromEntry(BB2));
        EXPECT_FALSE(DT->isReachableFromEntry(BB3));
        EXPECT_TRUE(DT->isReachableFromEntry(BB4));

        // BB dominance
        EXPECT_TRUE(DT->dominates(BB0, BB0));
        EXPECT_TRUE(DT->dominates(BB0, BB1));
        EXPECT_TRUE(DT->dominates(BB0, BB2));
        EXPECT_TRUE(DT->dominates(BB0, BB3));
        EXPECT_TRUE(DT->dominates(BB0, BB4));

        EXPECT_FALSE(DT->dominates(BB1, BB0));
        EXPECT_TRUE(DT->dominates(BB1, BB1));
        EXPECT_FALSE(DT->dominates(BB1, BB2));
        EXPECT_TRUE(DT->dominates(BB1, BB3));
        EXPECT_FALSE(DT->dominates(BB1, BB4));

        EXPECT_FALSE(DT->dominates(BB2, BB0));
        EXPECT_FALSE(DT->dominates(BB2, BB1));
        EXPECT_TRUE(DT->dominates(BB2, BB2));
        EXPECT_TRUE(DT->dominates(BB2, BB3));
        EXPECT_FALSE(DT->dominates(BB2, BB4));

        EXPECT_FALSE(DT->dominates(BB3, BB0));
        EXPECT_FALSE(DT->dominates(BB3, BB1));
        EXPECT_FALSE(DT->dominates(BB3, BB2));
        EXPECT_TRUE(DT->dominates(BB3, BB3));
        EXPECT_FALSE(DT->dominates(BB3, BB4));

        // BB proper dominance
        EXPECT_FALSE(DT->properlyDominates(BB0, BB0));
        EXPECT_TRUE(DT->properlyDominates(BB0, BB1));
        EXPECT_TRUE(DT->properlyDominates(BB0, BB2));
        EXPECT_TRUE(DT->properlyDominates(BB0, BB3));

        EXPECT_FALSE(DT->properlyDominates(BB1, BB0));
        EXPECT_FALSE(DT->properlyDominates(BB1, BB1));
        EXPECT_FALSE(DT->properlyDominates(BB1, BB2));
        EXPECT_TRUE(DT->properlyDominates(BB1, BB3));

        EXPECT_FALSE(DT->properlyDominates(BB2, BB0));
        EXPECT_FALSE(DT->properlyDominates(BB2, BB1));
        EXPECT_FALSE(DT->properlyDominates(BB2, BB2));
        EXPECT_TRUE(DT->properlyDominates(BB2, BB3));

        EXPECT_FALSE(DT->properlyDominates(BB3, BB0));
        EXPECT_FALSE(DT->properlyDominates(BB3, BB1));
        EXPECT_FALSE(DT->properlyDominates(BB3, BB2));
        EXPECT_FALSE(DT->properlyDominates(BB3, BB3));

        // Instruction dominance in the same reachable BB
        EXPECT_FALSE(DT->dominates(Y1, Y1));
        EXPECT_TRUE(DT->dominates(Y1, Y2));
        EXPECT_FALSE(DT->dominates(Y2, Y1));
        EXPECT_FALSE(DT->dominates(Y2, Y2));

        // Instruction dominance in the same unreachable BB
        EXPECT_TRUE(DT->dominates(Y6, Y6));
        EXPECT_TRUE(DT->dominates(Y6, Y7));
        EXPECT_TRUE(DT->dominates(Y7, Y6));
        EXPECT_TRUE(DT->dominates(Y7, Y7));

        // Invoke
        EXPECT_TRUE(DT->dominates(Y3, Y4));
        EXPECT_FALSE(DT->dominates(Y3, Y5));

        // Phi
        EXPECT_TRUE(DT->dominates(Y2, Y9));
        EXPECT_FALSE(DT->dominates(Y3, Y9));
        EXPECT_FALSE(DT->dominates(Y8, Y9));

        // Anything dominates unreachable
        EXPECT_TRUE(DT->dominates(Y1, Y6));
        EXPECT_TRUE(DT->dominates(Y3, Y6));

        // Unreachable doesn't dominate reachable
        EXPECT_FALSE(DT->dominates(Y6, Y1));

        // Instruction, BB dominance
        EXPECT_FALSE(DT->dominates(Y1, BB0));
        EXPECT_TRUE(DT->dominates(Y1, BB1));
        EXPECT_TRUE(DT->dominates(Y1, BB2));
        EXPECT_TRUE(DT->dominates(Y1, BB3));
        EXPECT_TRUE(DT->dominates(Y1, BB4));

        EXPECT_FALSE(DT->dominates(Y3, BB0));
        EXPECT_TRUE(DT->dominates(Y3, BB1));
        EXPECT_FALSE(DT->dominates(Y3, BB2));
        EXPECT_TRUE(DT->dominates(Y3, BB3));
        EXPECT_FALSE(DT->dominates(Y3, BB4));

        EXPECT_TRUE(DT->dominates(Y6, BB3));

        // Post dominance.
        EXPECT_TRUE(PDT->dominates(BB0, BB0));
        EXPECT_FALSE(PDT->dominates(BB1, BB0));
        EXPECT_FALSE(PDT->dominates(BB2, BB0));
        EXPECT_FALSE(PDT->dominates(BB3, BB0));
        EXPECT_TRUE(PDT->dominates(BB4, BB1));

        // Dominance descendants.
        SmallVector<BasicBlock *, 8> DominatedBBs, PostDominatedBBs;

        DT->getDescendants(BB0, DominatedBBs);
        PDT->getDescendants(BB0, PostDominatedBBs);
        EXPECT_EQ(DominatedBBs.size(), 4UL);
        EXPECT_EQ(PostDominatedBBs.size(), 1UL);

        // BB3 is unreachable. It should have no dominators nor postdominators.
        DominatedBBs.clear();
        PostDominatedBBs.clear();
        DT->getDescendants(BB3, DominatedBBs);
        DT->getDescendants(BB3, PostDominatedBBs);
        EXPECT_EQ(DominatedBBs.size(), 0UL);
        EXPECT_EQ(PostDominatedBBs.size(), 0UL);

        // Check DFS Numbers before
        EXPECT_EQ(DT->getNode(BB0)->getDFSNumIn(), 0UL);
        EXPECT_EQ(DT->getNode(BB0)->getDFSNumOut(), 7UL);
        EXPECT_EQ(DT->getNode(BB1)->getDFSNumIn(), 1UL);
        EXPECT_EQ(DT->getNode(BB1)->getDFSNumOut(), 2UL);
        EXPECT_EQ(DT->getNode(BB2)->getDFSNumIn(), 5UL);
        EXPECT_EQ(DT->getNode(BB2)->getDFSNumOut(), 6UL);
        EXPECT_EQ(DT->getNode(BB4)->getDFSNumIn(), 3UL);
        EXPECT_EQ(DT->getNode(BB4)->getDFSNumOut(), 4UL);

        // Reattach block 3 to block 1 and recalculate
        BB1->getTerminator()->eraseFromParent();
        BranchInst::Create(BB4, BB3, ConstantInt::getTrue(F.getContext()), BB1);
        DT->recalculate(F);

        // Check DFS Numbers after
        EXPECT_EQ(DT->getNode(BB0)->getDFSNumIn(), 0UL);
        EXPECT_EQ(DT->getNode(BB0)->getDFSNumOut(), 9UL);
        EXPECT_EQ(DT->getNode(BB1)->getDFSNumIn(), 1UL);
        EXPECT_EQ(DT->getNode(BB1)->getDFSNumOut(), 4UL);
        EXPECT_EQ(DT->getNode(BB2)->getDFSNumIn(), 7UL);
        EXPECT_EQ(DT->getNode(BB2)->getDFSNumOut(), 8UL);
        EXPECT_EQ(DT->getNode(BB3)->getDFSNumIn(), 2UL);
        EXPECT_EQ(DT->getNode(BB3)->getDFSNumOut(), 3UL);
        EXPECT_EQ(DT->getNode(BB4)->getDFSNumIn(), 5UL);
        EXPECT_EQ(DT->getNode(BB4)->getDFSNumOut(), 6UL);

        // Change root node
        DT->verifyDomTree();
        BasicBlock *NewEntry = BasicBlock::Create(F.getContext(), "new_entry",
                                                  &F, BB0);
        BranchInst::Create(BB0, NewEntry);
        EXPECT_EQ(F.begin()->getName(), NewEntry->getName());
        EXPECT_TRUE(&F.getEntryBlock() == NewEntry);
        DT->setNewRoot(NewEntry);
        DT->verifyDomTree();

        return false;
      }
      void getAnalysisUsage(AnalysisUsage &AU) const override {
        AU.addRequired<DominatorTreeWrapperPass>();
        AU.addRequired<PostDominatorTreeWrapperPass>();
      }
      DPass() : FunctionPass(ID) {
        initializeDPassPass(*PassRegistry::getPassRegistry());
      }
    };
    char DPass::ID = 0;

    std::unique_ptr<Module> makeLLVMModule(LLVMContext &Context, DPass *P) {
      const char *ModuleString =
        "declare i32 @g()\n" \
        "define void @f(i32 %x) personality i32 ()* @g {\n" \
        "bb0:\n" \
        "  %y1 = add i32 %x, 1\n" \
        "  %y2 = add i32 %x, 1\n" \
        "  %y3 = invoke i32 @g() to label %bb1 unwind label %bb2\n" \
        "bb1:\n" \
        "  %y4 = add i32 %x, 1\n" \
        "  br label %bb4\n" \
        "bb2:\n" \
        "  %y5 = landingpad i32\n" \
        "          cleanup\n" \
        "  br label %bb4\n" \
        "bb3:\n" \
        "  %y6 = add i32 %x, 1\n" \
        "  %y7 = add i32 %x, 1\n" \
        "  ret void\n" \
        "bb4:\n" \
        "  %y8 = phi i32 [0, %bb2], [%y4, %bb1]\n"
        "  %y9 = phi i32 [0, %bb2], [%y4, %bb1]\n"
        "  ret void\n" \
        "}\n";
      SMDiagnostic Err;
      return parseAssemblyString(ModuleString, Err, Context);
    }

    TEST(DominatorTree, Unreachable) {
      DPass *P = new DPass();
      LLVMContext Context;
      std::unique_ptr<Module> M = makeLLVMModule(Context, P);
      legacy::PassManager Passes;
      Passes.add(P);
      Passes.run(*M);
    }
  }
}

INITIALIZE_PASS_BEGIN(DPass, "dpass", "dpass", false, false)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
INITIALIZE_PASS_END(DPass, "dpass", "dpass", false, false)
<commit_msg>clang-format DomTree unittest<commit_after>//===- llvm/unittests/IR/DominatorTreeTest.cpp - Constants unit tests -----===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/Analysis/PostDominators.h"
#include "llvm/AsmParser/Parser.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/SourceMgr.h"
#include "gtest/gtest.h"

using namespace llvm;

namespace llvm {
void initializeDPassPass(PassRegistry &);

namespace {
struct DPass : public FunctionPass {
  static char ID;
  bool runOnFunction(Function &F) override {
    DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
    PostDominatorTree *PDT =
        &getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
    Function::iterator FI = F.begin();

    BasicBlock *BB0 = &*FI++;
    BasicBlock::iterator BBI = BB0->begin();
    Instruction *Y1 = &*BBI++;
    Instruction *Y2 = &*BBI++;
    Instruction *Y3 = &*BBI++;

    BasicBlock *BB1 = &*FI++;
    BBI = BB1->begin();
    Instruction *Y4 = &*BBI++;

    BasicBlock *BB2 = &*FI++;
    BBI = BB2->begin();
    Instruction *Y5 = &*BBI++;

    BasicBlock *BB3 = &*FI++;
    BBI = BB3->begin();
    Instruction *Y6 = &*BBI++;
    Instruction *Y7 = &*BBI++;

    BasicBlock *BB4 = &*FI++;
    BBI = BB4->begin();
    Instruction *Y8 = &*BBI++;
    Instruction *Y9 = &*BBI++;

    // Reachability
    EXPECT_TRUE(DT->isReachableFromEntry(BB0));
    EXPECT_TRUE(DT->isReachableFromEntry(BB1));
    EXPECT_TRUE(DT->isReachableFromEntry(BB2));
    EXPECT_FALSE(DT->isReachableFromEntry(BB3));
    EXPECT_TRUE(DT->isReachableFromEntry(BB4));

    // BB dominance
    EXPECT_TRUE(DT->dominates(BB0, BB0));
    EXPECT_TRUE(DT->dominates(BB0, BB1));
    EXPECT_TRUE(DT->dominates(BB0, BB2));
    EXPECT_TRUE(DT->dominates(BB0, BB3));
    EXPECT_TRUE(DT->dominates(BB0, BB4));

    EXPECT_FALSE(DT->dominates(BB1, BB0));
    EXPECT_TRUE(DT->dominates(BB1, BB1));
    EXPECT_FALSE(DT->dominates(BB1, BB2));
    EXPECT_TRUE(DT->dominates(BB1, BB3));
    EXPECT_FALSE(DT->dominates(BB1, BB4));

    EXPECT_FALSE(DT->dominates(BB2, BB0));
    EXPECT_FALSE(DT->dominates(BB2, BB1));
    EXPECT_TRUE(DT->dominates(BB2, BB2));
    EXPECT_TRUE(DT->dominates(BB2, BB3));
    EXPECT_FALSE(DT->dominates(BB2, BB4));

    EXPECT_FALSE(DT->dominates(BB3, BB0));
    EXPECT_FALSE(DT->dominates(BB3, BB1));
    EXPECT_FALSE(DT->dominates(BB3, BB2));
    EXPECT_TRUE(DT->dominates(BB3, BB3));
    EXPECT_FALSE(DT->dominates(BB3, BB4));

    // BB proper dominance
    EXPECT_FALSE(DT->properlyDominates(BB0, BB0));
    EXPECT_TRUE(DT->properlyDominates(BB0, BB1));
    EXPECT_TRUE(DT->properlyDominates(BB0, BB2));
    EXPECT_TRUE(DT->properlyDominates(BB0, BB3));

    EXPECT_FALSE(DT->properlyDominates(BB1, BB0));
    EXPECT_FALSE(DT->properlyDominates(BB1, BB1));
    EXPECT_FALSE(DT->properlyDominates(BB1, BB2));
    EXPECT_TRUE(DT->properlyDominates(BB1, BB3));

    EXPECT_FALSE(DT->properlyDominates(BB2, BB0));
    EXPECT_FALSE(DT->properlyDominates(BB2, BB1));
    EXPECT_FALSE(DT->properlyDominates(BB2, BB2));
    EXPECT_TRUE(DT->properlyDominates(BB2, BB3));

    EXPECT_FALSE(DT->properlyDominates(BB3, BB0));
    EXPECT_FALSE(DT->properlyDominates(BB3, BB1));
    EXPECT_FALSE(DT->properlyDominates(BB3, BB2));
    EXPECT_FALSE(DT->properlyDominates(BB3, BB3));

    // Instruction dominance in the same reachable BB
    EXPECT_FALSE(DT->dominates(Y1, Y1));
    EXPECT_TRUE(DT->dominates(Y1, Y2));
    EXPECT_FALSE(DT->dominates(Y2, Y1));
    EXPECT_FALSE(DT->dominates(Y2, Y2));

    // Instruction dominance in the same unreachable BB
    EXPECT_TRUE(DT->dominates(Y6, Y6));
    EXPECT_TRUE(DT->dominates(Y6, Y7));
    EXPECT_TRUE(DT->dominates(Y7, Y6));
    EXPECT_TRUE(DT->dominates(Y7, Y7));

    // Invoke
    EXPECT_TRUE(DT->dominates(Y3, Y4));
    EXPECT_FALSE(DT->dominates(Y3, Y5));

    // Phi
    EXPECT_TRUE(DT->dominates(Y2, Y9));
    EXPECT_FALSE(DT->dominates(Y3, Y9));
    EXPECT_FALSE(DT->dominates(Y8, Y9));

    // Anything dominates unreachable
    EXPECT_TRUE(DT->dominates(Y1, Y6));
    EXPECT_TRUE(DT->dominates(Y3, Y6));

    // Unreachable doesn't dominate reachable
    EXPECT_FALSE(DT->dominates(Y6, Y1));

    // Instruction, BB dominance
    EXPECT_FALSE(DT->dominates(Y1, BB0));
    EXPECT_TRUE(DT->dominates(Y1, BB1));
    EXPECT_TRUE(DT->dominates(Y1, BB2));
    EXPECT_TRUE(DT->dominates(Y1, BB3));
    EXPECT_TRUE(DT->dominates(Y1, BB4));

    EXPECT_FALSE(DT->dominates(Y3, BB0));
    EXPECT_TRUE(DT->dominates(Y3, BB1));
    EXPECT_FALSE(DT->dominates(Y3, BB2));
    EXPECT_TRUE(DT->dominates(Y3, BB3));
    EXPECT_FALSE(DT->dominates(Y3, BB4));

    EXPECT_TRUE(DT->dominates(Y6, BB3));

    // Post dominance.
    EXPECT_TRUE(PDT->dominates(BB0, BB0));
    EXPECT_FALSE(PDT->dominates(BB1, BB0));
    EXPECT_FALSE(PDT->dominates(BB2, BB0));
    EXPECT_FALSE(PDT->dominates(BB3, BB0));
    EXPECT_TRUE(PDT->dominates(BB4, BB1));

    // Dominance descendants.
    SmallVector<BasicBlock *, 8> DominatedBBs, PostDominatedBBs;

    DT->getDescendants(BB0, DominatedBBs);
    PDT->getDescendants(BB0, PostDominatedBBs);
    EXPECT_EQ(DominatedBBs.size(), 4UL);
    EXPECT_EQ(PostDominatedBBs.size(), 1UL);

    // BB3 is unreachable. It should have no dominators nor postdominators.
    DominatedBBs.clear();
    PostDominatedBBs.clear();
    DT->getDescendants(BB3, DominatedBBs);
    DT->getDescendants(BB3, PostDominatedBBs);
    EXPECT_EQ(DominatedBBs.size(), 0UL);
    EXPECT_EQ(PostDominatedBBs.size(), 0UL);

    // Check DFS Numbers before
    EXPECT_EQ(DT->getNode(BB0)->getDFSNumIn(), 0UL);
    EXPECT_EQ(DT->getNode(BB0)->getDFSNumOut(), 7UL);
    EXPECT_EQ(DT->getNode(BB1)->getDFSNumIn(), 1UL);
    EXPECT_EQ(DT->getNode(BB1)->getDFSNumOut(), 2UL);
    EXPECT_EQ(DT->getNode(BB2)->getDFSNumIn(), 5UL);
    EXPECT_EQ(DT->getNode(BB2)->getDFSNumOut(), 6UL);
    EXPECT_EQ(DT->getNode(BB4)->getDFSNumIn(), 3UL);
    EXPECT_EQ(DT->getNode(BB4)->getDFSNumOut(), 4UL);

    // Reattach block 3 to block 1 and recalculate
    BB1->getTerminator()->eraseFromParent();
    BranchInst::Create(BB4, BB3, ConstantInt::getTrue(F.getContext()), BB1);
    DT->recalculate(F);

    // Check DFS Numbers after
    EXPECT_EQ(DT->getNode(BB0)->getDFSNumIn(), 0UL);
    EXPECT_EQ(DT->getNode(BB0)->getDFSNumOut(), 9UL);
    EXPECT_EQ(DT->getNode(BB1)->getDFSNumIn(), 1UL);
    EXPECT_EQ(DT->getNode(BB1)->getDFSNumOut(), 4UL);
    EXPECT_EQ(DT->getNode(BB2)->getDFSNumIn(), 7UL);
    EXPECT_EQ(DT->getNode(BB2)->getDFSNumOut(), 8UL);
    EXPECT_EQ(DT->getNode(BB3)->getDFSNumIn(), 2UL);
    EXPECT_EQ(DT->getNode(BB3)->getDFSNumOut(), 3UL);
    EXPECT_EQ(DT->getNode(BB4)->getDFSNumIn(), 5UL);
    EXPECT_EQ(DT->getNode(BB4)->getDFSNumOut(), 6UL);

    // Change root node
    DT->verifyDomTree();
    BasicBlock *NewEntry =
        BasicBlock::Create(F.getContext(), "new_entry", &F, BB0);
    BranchInst::Create(BB0, NewEntry);
    EXPECT_EQ(F.begin()->getName(), NewEntry->getName());
    EXPECT_TRUE(&F.getEntryBlock() == NewEntry);
    DT->setNewRoot(NewEntry);
    DT->verifyDomTree();

    return false;
  }
  void getAnalysisUsage(AnalysisUsage &AU) const override {
    AU.addRequired<DominatorTreeWrapperPass>();
    AU.addRequired<PostDominatorTreeWrapperPass>();
  }
  DPass() : FunctionPass(ID) {
    initializeDPassPass(*PassRegistry::getPassRegistry());
  }
};
char DPass::ID = 0;

std::unique_ptr<Module> makeLLVMModule(LLVMContext &Context, DPass *P) {
  const char *ModuleString =
      "declare i32 @g()\n"
      "define void @f(i32 %x) personality i32 ()* @g {\n"
      "bb0:\n"
      "  %y1 = add i32 %x, 1\n"
      "  %y2 = add i32 %x, 1\n"
      "  %y3 = invoke i32 @g() to label %bb1 unwind label %bb2\n"
      "bb1:\n"
      "  %y4 = add i32 %x, 1\n"
      "  br label %bb4\n"
      "bb2:\n"
      "  %y5 = landingpad i32\n"
      "          cleanup\n"
      "  br label %bb4\n"
      "bb3:\n"
      "  %y6 = add i32 %x, 1\n"
      "  %y7 = add i32 %x, 1\n"
      "  ret void\n"
      "bb4:\n"
      "  %y8 = phi i32 [0, %bb2], [%y4, %bb1]\n"
      "  %y9 = phi i32 [0, %bb2], [%y4, %bb1]\n"
      "  ret void\n"
      "}\n";
  SMDiagnostic Err;
  return parseAssemblyString(ModuleString, Err, Context);
}

TEST(DominatorTree, Unreachable) {
  DPass *P = new DPass();
  LLVMContext Context;
  std::unique_ptr<Module> M = makeLLVMModule(Context, P);
  legacy::PassManager Passes;
  Passes.add(P);
  Passes.run(*M);
}
} // namespace
} // namespace llvm

INITIALIZE_PASS_BEGIN(DPass, "dpass", "dpass", false, false)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
INITIALIZE_PASS_END(DPass, "dpass", "dpass", false, false)
<|endoftext|>


<commit_before>// ROOT6 modifications
#ifdef __CLING__
#include <AliAnalysisManager.h>
#include <AliAODInputHandler.h>
#include <AliDielectronVarCuts.h>

// Tell ROOT where to find AliPhysics headers
R__ADD_INCLUDE_PATH($ALICE_PHYSICS)
#endif

AliAnalysisTask *AddTask_sscheid_lowmass(Bool_t getFromAlien=kFALSE,
                                             TString cFileName = "Config_sscheid_lowmass_06.C",
                                             int nDie = 0,
                                             TString outputFileName="LMEE.root",
                                             ULong64_t triggerMask = AliVEvent::kINT7
                                             )
{

  //get the current analysis manager
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTask_sscheid_lowmass", "No analysis manager found.");
    return 0;
  }

  //Base Directory for GRID / LEGO Train
  TString configBasePath= "$ALICE_PHYSICS/PWGDQ/dielectron/macrosLMEE/";
  if(getFromAlien && (!gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/h/hscheid/PWGDQ/dielectron/macrosLMEE/%s .",cFileName.Data()))) ){
    configBasePath=Form("%s/",gSystem->pwd());
  }

  TString configFilePath(configBasePath+cFileName);

  std::cout << "Configpath:  " << configFilePath << std::endl;

  //Do we have an MC handler?
  Bool_t hasMC = (AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0);

  //if (!gROOT->GetListOfGlobalFunctions()->FindObject(cFileName.Data()))

  //create task and add it to the manager (MB)
  AliAnalysisTaskMultiDielectron *task = new AliAnalysisTaskMultiDielectron("MultiDielectron");
  if (!hasMC) task->UsePhysicsSelection();
  task->SetTriggerMask(triggerMask);
  //  taskMB->SetRejectPileup();

  // task->SetRandomizeDaughters(randomizeDau); //default kFALSE

  //Add event filter
  // task->SetEventFilter( GetEventCuts() );

  mgr->AddTask(task);

  //add dielectron analysis with different cuts to the task
  #if defined(__CLING__)
    TMacro conf_die(gSystem->ExpandPathName(configFilePath.Data())); //ROOT6
    for (Int_t i=0; i<nDie; ++i){ //nDie as argument of add task
      AliDielectron *diel_low = reinterpret_cast<AliDielectron *>(conf_die.Exec(Form("%i",i)));
      if(!diel_low)continue;
      task->AddDielectron(diel_low);
    }
  #elif defined(__CINT__)
    gROOT->LoadMacro(configFilePath.Data()); //ROOT5 syntax
    for (Int_t i=0; i<nDie; ++i){ //nDie defined in config file
      AliDielectron *diel_low = Config_sscheid_lowmass(i); // also ROOT5
      if(!diel_low)continue;
      task->AddDielectron(diel_low);
    }
  #endif

  // std::cout << "Mixing is set to: " << diel_low->GetMixing() << syd::endl;

  //create output container
  AliAnalysisDataContainer *coutput1 =
    mgr->CreateContainer("tree_lowmass",
                         TTree::Class(),
                         AliAnalysisManager::kExchangeContainer,
                         outputFileName.Data());

  AliAnalysisDataContainer *cOutputHist1 =
    mgr->CreateContainer("Histos_diel_lowmass",
                         TList::Class(),
                         AliAnalysisManager::kOutputContainer,
                         outputFileName.Data());

  AliAnalysisDataContainer *cOutputHist2 =
    mgr->CreateContainer("CF_diel_lowmass",
                         TList::Class(),
                         AliAnalysisManager::kOutputContainer,
                         outputFileName.Data());

  AliAnalysisDataContainer *cOutputHist3 =
    mgr->CreateContainer("sscheid_lowmass_EventStat",
                         TH1D::Class(),
                         AliAnalysisManager::kOutputContainer,
                         outputFileName.Data());

  mgr->ConnectInput(task,  0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(task, 0, coutput1 );
  mgr->ConnectOutput(task, 1, cOutputHist1);
  mgr->ConnectOutput(task, 2, cOutputHist2);
  mgr->ConnectOutput(task, 3, cOutputHist3);
  return task;
}
<commit_msg>Added protection in AddTask for config file copy from alien.<commit_after>// ROOT6 modifications
#ifdef __CLING__
#include <AliAnalysisManager.h>
#include <AliAODInputHandler.h>
#include <AliDielectronVarCuts.h>

// Tell ROOT where to find AliPhysics headers
R__ADD_INCLUDE_PATH($ALICE_PHYSICS)
#endif

AliAnalysisTask *AddTask_sscheid_lowmass(Bool_t getFromAlien=kFALSE,
                                             TString cFileName = "Config_sscheid_lowmass_06.C",
                                             int nDie = 0,
                                             TString outputFileName="LMEE.root",
                                             ULong64_t triggerMask = AliVEvent::kINT7
                                             )
{

  //get the current analysis manager
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTask_sscheid_lowmass", "No analysis manager found.");
    return 0;
  }

  //Base Directory for GRID / LEGO Train
  TString configBasePath= "$ALICE_PHYSICS/PWGDQ/dielectron/macrosLMEE/";

  if (!gSystem->AccessPathName(cFileName))
  {
    printf("file already present\n");
    configBasePath=Form("%s/",gSystem->pwd());
  }
  else if(getFromAlien && (!gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/h/hscheid/PWGDQ/dielectron/macrosLMEE/%s .",cFileName.Data()))) )
  {
    configBasePath=Form("%s/",gSystem->pwd());
  }

  TString configFilePath(configBasePath+cFileName);

  std::cout << "Configpath:  " << configFilePath << std::endl;

  //Do we have an MC handler?
  Bool_t hasMC = (AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0);

  //if (!gROOT->GetListOfGlobalFunctions()->FindObject(cFileName.Data()))

  //create task and add it to the manager (MB)
  AliAnalysisTaskMultiDielectron *task = new AliAnalysisTaskMultiDielectron("MultiDielectron");
  if (!hasMC) task->UsePhysicsSelection();
  task->SetTriggerMask(triggerMask);
  //  taskMB->SetRejectPileup();

  // task->SetRandomizeDaughters(randomizeDau); //default kFALSE

  //Add event filter
  // task->SetEventFilter( GetEventCuts() );

  mgr->AddTask(task);

  //add dielectron analysis with different cuts to the task
  #if defined(__CLING__)
    TMacro conf_die(gSystem->ExpandPathName(configFilePath.Data())); //ROOT6
    for (Int_t i=0; i<nDie; ++i){ //nDie as argument of add task
      AliDielectron *diel_low = reinterpret_cast<AliDielectron *>(conf_die.Exec(Form("%i",i)));
      if(!diel_low)continue;
      task->AddDielectron(diel_low);
    }
  #elif defined(__CINT__)
    gROOT->LoadMacro(configFilePath.Data()); //ROOT5 syntax
    for (Int_t i=0; i<nDie; ++i){ //nDie defined in config file
      AliDielectron *diel_low = Config_sscheid_lowmass(i); // also ROOT5
      if(!diel_low)continue;
      task->AddDielectron(diel_low);
    }
  #endif

  // std::cout << "Mixing is set to: " << diel_low->GetMixing() << syd::endl;

  //create output container
  AliAnalysisDataContainer *coutput1 =
    mgr->CreateContainer("tree_lowmass",
                         TTree::Class(),
                         AliAnalysisManager::kExchangeContainer,
                         outputFileName.Data());

  AliAnalysisDataContainer *cOutputHist1 =
    mgr->CreateContainer("Histos_diel_lowmass",
                         TList::Class(),
                         AliAnalysisManager::kOutputContainer,
                         outputFileName.Data());

  AliAnalysisDataContainer *cOutputHist2 =
    mgr->CreateContainer("CF_diel_lowmass",
                         TList::Class(),
                         AliAnalysisManager::kOutputContainer,
                         outputFileName.Data());

  AliAnalysisDataContainer *cOutputHist3 =
    mgr->CreateContainer("sscheid_lowmass_EventStat",
                         TH1D::Class(),
                         AliAnalysisManager::kOutputContainer,
                         outputFileName.Data());

  mgr->ConnectInput(task,  0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(task, 0, coutput1 );
  mgr->ConnectOutput(task, 1, cOutputHist1);
  mgr->ConnectOutput(task, 2, cOutputHist2);
  mgr->ConnectOutput(task, 3, cOutputHist3);
  return task;
}
<|endoftext|>


<commit_before>//===-- ArchSpecTest.cpp ----------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "gtest/gtest.h"

#include "lldb/Utility/ArchSpec.h"
#include "llvm/BinaryFormat/MachO.h"

using namespace lldb;
using namespace lldb_private;

TEST(ArchSpecTest, TestParseMachCPUDashSubtypeTripleSimple) {

  // Success conditions.  Valid cpu/subtype combinations using both - and .
  ArchSpec AS;
  EXPECT_TRUE(ParseMachCPUDashSubtypeTriple("12-10", AS));
  EXPECT_EQ(12u, AS.GetMachOCPUType());
  EXPECT_EQ(10u, AS.GetMachOCPUSubType());

  AS = ArchSpec();
  EXPECT_TRUE(ParseMachCPUDashSubtypeTriple("12-15", AS));
  EXPECT_EQ(12u, AS.GetMachOCPUType());
  EXPECT_EQ(15u, AS.GetMachOCPUSubType());

  AS = ArchSpec();
  EXPECT_TRUE(ParseMachCPUDashSubtypeTriple("12.15", AS));
  EXPECT_EQ(12u, AS.GetMachOCPUType());
  EXPECT_EQ(15u, AS.GetMachOCPUSubType());

  // Failure conditions.

  // Valid string, unknown cpu/subtype.
  AS = ArchSpec();
  EXPECT_TRUE(ParseMachCPUDashSubtypeTriple("13.11", AS));
  EXPECT_EQ(0u, AS.GetMachOCPUType());
  EXPECT_EQ(0u, AS.GetMachOCPUSubType());

  // Missing / invalid cpu or subtype
  AS = ArchSpec();
  EXPECT_FALSE(ParseMachCPUDashSubtypeTriple("13", AS));

  AS = ArchSpec();
  EXPECT_FALSE(ParseMachCPUDashSubtypeTriple("13.A", AS));

  AS = ArchSpec();
  EXPECT_FALSE(ParseMachCPUDashSubtypeTriple("A.13", AS));

  // Empty string.
  AS = ArchSpec();
  EXPECT_FALSE(ParseMachCPUDashSubtypeTriple("", AS));
}

TEST(ArchSpecTest, TestParseMachCPUDashSubtypeTripleExtra) {
  ArchSpec AS;
  EXPECT_TRUE(ParseMachCPUDashSubtypeTriple("12-15-vendor-os", AS));
  EXPECT_EQ(12u, AS.GetMachOCPUType());
  EXPECT_EQ(15u, AS.GetMachOCPUSubType());
  EXPECT_EQ("vendor", AS.GetTriple().getVendorName());
  EXPECT_EQ("os", AS.GetTriple().getOSName());

  AS = ArchSpec();
  EXPECT_TRUE(ParseMachCPUDashSubtypeTriple("12-10-vendor-os-name", AS));
  EXPECT_EQ(12u, AS.GetMachOCPUType());
  EXPECT_EQ(10u, AS.GetMachOCPUSubType());
  EXPECT_EQ("vendor", AS.GetTriple().getVendorName());
  EXPECT_EQ("os", AS.GetTriple().getOSName());

  AS = ArchSpec();
  EXPECT_TRUE(ParseMachCPUDashSubtypeTriple("12-15-vendor.os-name", AS));
  EXPECT_EQ(12u, AS.GetMachOCPUType());
  EXPECT_EQ(15u, AS.GetMachOCPUSubType());
  EXPECT_EQ("vendor.os", AS.GetTriple().getVendorName());
  EXPECT_EQ("name", AS.GetTriple().getOSName());

  // These there should parse correctly, but the vendor / OS should be defaulted
  // since they are unrecognized.
  AS = ArchSpec();
  EXPECT_TRUE(ParseMachCPUDashSubtypeTriple("12-10-vendor", AS));
  EXPECT_EQ(12u, AS.GetMachOCPUType());
  EXPECT_EQ(10u, AS.GetMachOCPUSubType());
  EXPECT_EQ("apple", AS.GetTriple().getVendorName());
  EXPECT_EQ("", AS.GetTriple().getOSName());

  AS = ArchSpec();
  EXPECT_FALSE(ParseMachCPUDashSubtypeTriple("12.10.10", AS));

  AS = ArchSpec();
  EXPECT_FALSE(ParseMachCPUDashSubtypeTriple("12-10.10", AS));
}

TEST(ArchSpecTest, TestSetTriple) {
  ArchSpec AS;

  // Various flavors of valid triples.
  EXPECT_TRUE(AS.SetTriple("12-10-apple-darwin"));
  EXPECT_EQ(uint32_t(llvm::MachO::CPU_TYPE_ARM), AS.GetMachOCPUType());
  EXPECT_EQ(10u, AS.GetMachOCPUSubType());
  EXPECT_TRUE(llvm::StringRef(AS.GetTriple().str())
                  .consume_front("armv7f-apple-darwin"));
  EXPECT_EQ(ArchSpec::eCore_arm_armv7f, AS.GetCore());

  AS = ArchSpec();
  EXPECT_TRUE(AS.SetTriple("18.100-apple-darwin"));
  EXPECT_EQ(uint32_t(llvm::MachO::CPU_TYPE_POWERPC), AS.GetMachOCPUType());
  EXPECT_EQ(100u, AS.GetMachOCPUSubType());
  EXPECT_TRUE(llvm::StringRef(AS.GetTriple().str())
                  .consume_front("powerpc-apple-darwin"));
  EXPECT_EQ(ArchSpec::eCore_ppc_ppc970, AS.GetCore());

  AS = ArchSpec();
  EXPECT_TRUE(AS.SetTriple("i686-pc-windows"));
  EXPECT_EQ(llvm::Triple::x86, AS.GetTriple().getArch());
  EXPECT_EQ(llvm::Triple::PC, AS.GetTriple().getVendor());
  EXPECT_EQ(llvm::Triple::Win32, AS.GetTriple().getOS());
  EXPECT_TRUE(
      llvm::StringRef(AS.GetTriple().str()).consume_front("i686-pc-windows"));
  EXPECT_STREQ("i686", AS.GetArchitectureName());
  EXPECT_EQ(ArchSpec::eCore_x86_32_i686, AS.GetCore());

  // Various flavors of invalid triples.
  AS = ArchSpec();
  EXPECT_FALSE(AS.SetTriple("unknown-unknown-unknown"));

  AS = ArchSpec();
  EXPECT_FALSE(AS.SetTriple("unknown"));

  AS = ArchSpec();
  EXPECT_FALSE(AS.SetTriple(""));
}

TEST(ArchSpecTest, MergeFrom) {
  ArchSpec A;
  ArchSpec B("x86_64-pc-linux");

  EXPECT_FALSE(A.IsValid());
  ASSERT_TRUE(B.IsValid());
  EXPECT_EQ(llvm::Triple::ArchType::x86_64, B.GetTriple().getArch());
  EXPECT_EQ(llvm::Triple::VendorType::PC, B.GetTriple().getVendor());
  EXPECT_EQ(llvm::Triple::OSType::Linux, B.GetTriple().getOS());
  EXPECT_EQ(ArchSpec::eCore_x86_64_x86_64, B.GetCore());

  A.MergeFrom(B);
  ASSERT_TRUE(A.IsValid());
  EXPECT_EQ(llvm::Triple::ArchType::x86_64, A.GetTriple().getArch());
  EXPECT_EQ(llvm::Triple::VendorType::PC, A.GetTriple().getVendor());
  EXPECT_EQ(llvm::Triple::OSType::Linux, A.GetTriple().getOS());
  EXPECT_EQ(ArchSpec::eCore_x86_64_x86_64, A.GetCore());
}

TEST(ArchSpecTest, MergeFromMachOUnknown) {
  class MyArchSpec : public ArchSpec {
  public:
    MyArchSpec() {
      this->SetTriple("unknown-mach-64");
      this->m_core = ArchSpec::eCore_uknownMach64;
      this->m_byte_order = eByteOrderLittle;
      this->m_flags = 0;
    }
  };

  MyArchSpec A;
  ASSERT_TRUE(A.IsValid());
  MyArchSpec B;
  ASSERT_TRUE(B.IsValid());
  A.MergeFrom(B);
  ASSERT_EQ(A.GetCore(), ArchSpec::eCore_uknownMach64);
}

TEST(ArchSpecTest, Compatibility) {
  {
    ArchSpec A("x86_64-apple-macosx10.12");
    ArchSpec B("x86_64-apple-macosx10.12");
    ASSERT_TRUE(A.IsExactMatch(B));
    ASSERT_TRUE(A.IsCompatibleMatch(B));
  }
  {
    // The version information is auxiliary to support availablity but
    // doesn't affect compatibility.
    ArchSpec A("x86_64-apple-macosx10.11");
    ArchSpec B("x86_64-apple-macosx10.12");
    ASSERT_TRUE(A.IsExactMatch(B));
    ASSERT_TRUE(A.IsCompatibleMatch(B));
  }
  {
    ArchSpec A("x86_64-apple-macosx10.13");
    ArchSpec B("x86_64h-apple-macosx10.13");
    ASSERT_FALSE(A.IsExactMatch(B));
    ASSERT_TRUE(A.IsCompatibleMatch(B));
  }
  {
    ArchSpec A("x86_64-apple-macosx");
    ArchSpec B("x86_64-apple-ios-simulator");
    ASSERT_FALSE(A.IsExactMatch(B));
    ASSERT_FALSE(A.IsCompatibleMatch(B));
  }
  {
    ArchSpec A("x86_64-*-*");
    ArchSpec B("x86_64-apple-ios-simulator");
    ASSERT_FALSE(A.IsExactMatch(B));
    ASSERT_FALSE(A.IsCompatibleMatch(B));
  }
  {
    ArchSpec A("arm64-*-*");
    ArchSpec B("arm64-apple-ios");
    ASSERT_FALSE(A.IsExactMatch(B));
    // FIXME: This looks unintuitive and we should investigate whether
    // thi is the desired behavior.
    ASSERT_FALSE(A.IsCompatibleMatch(B));
  }
  {
    ArchSpec A("x86_64-*-*");
    ArchSpec B("x86_64-apple-ios-simulator");
    ASSERT_FALSE(A.IsExactMatch(B));
    // FIXME: See above, though the extra environment complicates things.
    ASSERT_FALSE(A.IsCompatibleMatch(B));
  }
}
<commit_msg>Add another ArchSpec unit test.<commit_after>//===-- ArchSpecTest.cpp ----------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "gtest/gtest.h"

#include "lldb/Utility/ArchSpec.h"
#include "llvm/BinaryFormat/MachO.h"

using namespace lldb;
using namespace lldb_private;

TEST(ArchSpecTest, TestParseMachCPUDashSubtypeTripleSimple) {

  // Success conditions.  Valid cpu/subtype combinations using both - and .
  ArchSpec AS;
  EXPECT_TRUE(ParseMachCPUDashSubtypeTriple("12-10", AS));
  EXPECT_EQ(12u, AS.GetMachOCPUType());
  EXPECT_EQ(10u, AS.GetMachOCPUSubType());

  AS = ArchSpec();
  EXPECT_TRUE(ParseMachCPUDashSubtypeTriple("12-15", AS));
  EXPECT_EQ(12u, AS.GetMachOCPUType());
  EXPECT_EQ(15u, AS.GetMachOCPUSubType());

  AS = ArchSpec();
  EXPECT_TRUE(ParseMachCPUDashSubtypeTriple("12.15", AS));
  EXPECT_EQ(12u, AS.GetMachOCPUType());
  EXPECT_EQ(15u, AS.GetMachOCPUSubType());

  // Failure conditions.

  // Valid string, unknown cpu/subtype.
  AS = ArchSpec();
  EXPECT_TRUE(ParseMachCPUDashSubtypeTriple("13.11", AS));
  EXPECT_EQ(0u, AS.GetMachOCPUType());
  EXPECT_EQ(0u, AS.GetMachOCPUSubType());

  // Missing / invalid cpu or subtype
  AS = ArchSpec();
  EXPECT_FALSE(ParseMachCPUDashSubtypeTriple("13", AS));

  AS = ArchSpec();
  EXPECT_FALSE(ParseMachCPUDashSubtypeTriple("13.A", AS));

  AS = ArchSpec();
  EXPECT_FALSE(ParseMachCPUDashSubtypeTriple("A.13", AS));

  // Empty string.
  AS = ArchSpec();
  EXPECT_FALSE(ParseMachCPUDashSubtypeTriple("", AS));
}

TEST(ArchSpecTest, TestParseMachCPUDashSubtypeTripleExtra) {
  ArchSpec AS;
  EXPECT_TRUE(ParseMachCPUDashSubtypeTriple("12-15-vendor-os", AS));
  EXPECT_EQ(12u, AS.GetMachOCPUType());
  EXPECT_EQ(15u, AS.GetMachOCPUSubType());
  EXPECT_EQ("vendor", AS.GetTriple().getVendorName());
  EXPECT_EQ("os", AS.GetTriple().getOSName());

  AS = ArchSpec();
  EXPECT_TRUE(ParseMachCPUDashSubtypeTriple("12-10-vendor-os-name", AS));
  EXPECT_EQ(12u, AS.GetMachOCPUType());
  EXPECT_EQ(10u, AS.GetMachOCPUSubType());
  EXPECT_EQ("vendor", AS.GetTriple().getVendorName());
  EXPECT_EQ("os", AS.GetTriple().getOSName());

  AS = ArchSpec();
  EXPECT_TRUE(ParseMachCPUDashSubtypeTriple("12-15-vendor.os-name", AS));
  EXPECT_EQ(12u, AS.GetMachOCPUType());
  EXPECT_EQ(15u, AS.GetMachOCPUSubType());
  EXPECT_EQ("vendor.os", AS.GetTriple().getVendorName());
  EXPECT_EQ("name", AS.GetTriple().getOSName());

  // These there should parse correctly, but the vendor / OS should be defaulted
  // since they are unrecognized.
  AS = ArchSpec();
  EXPECT_TRUE(ParseMachCPUDashSubtypeTriple("12-10-vendor", AS));
  EXPECT_EQ(12u, AS.GetMachOCPUType());
  EXPECT_EQ(10u, AS.GetMachOCPUSubType());
  EXPECT_EQ("apple", AS.GetTriple().getVendorName());
  EXPECT_EQ("", AS.GetTriple().getOSName());

  AS = ArchSpec();
  EXPECT_FALSE(ParseMachCPUDashSubtypeTriple("12.10.10", AS));

  AS = ArchSpec();
  EXPECT_FALSE(ParseMachCPUDashSubtypeTriple("12-10.10", AS));
}

TEST(ArchSpecTest, TestSetTriple) {
  ArchSpec AS;

  // Various flavors of valid triples.
  EXPECT_TRUE(AS.SetTriple("12-10-apple-darwin"));
  EXPECT_EQ(uint32_t(llvm::MachO::CPU_TYPE_ARM), AS.GetMachOCPUType());
  EXPECT_EQ(10u, AS.GetMachOCPUSubType());
  EXPECT_TRUE(llvm::StringRef(AS.GetTriple().str())
                  .consume_front("armv7f-apple-darwin"));
  EXPECT_EQ(ArchSpec::eCore_arm_armv7f, AS.GetCore());

  AS = ArchSpec();
  EXPECT_TRUE(AS.SetTriple("18.100-apple-darwin"));
  EXPECT_EQ(uint32_t(llvm::MachO::CPU_TYPE_POWERPC), AS.GetMachOCPUType());
  EXPECT_EQ(100u, AS.GetMachOCPUSubType());
  EXPECT_TRUE(llvm::StringRef(AS.GetTriple().str())
                  .consume_front("powerpc-apple-darwin"));
  EXPECT_EQ(ArchSpec::eCore_ppc_ppc970, AS.GetCore());

  AS = ArchSpec();
  EXPECT_TRUE(AS.SetTriple("i686-pc-windows"));
  EXPECT_EQ(llvm::Triple::x86, AS.GetTriple().getArch());
  EXPECT_EQ(llvm::Triple::PC, AS.GetTriple().getVendor());
  EXPECT_EQ(llvm::Triple::Win32, AS.GetTriple().getOS());
  EXPECT_TRUE(
      llvm::StringRef(AS.GetTriple().str()).consume_front("i686-pc-windows"));
  EXPECT_STREQ("i686", AS.GetArchitectureName());
  EXPECT_EQ(ArchSpec::eCore_x86_32_i686, AS.GetCore());

  // Various flavors of invalid triples.
  AS = ArchSpec();
  EXPECT_FALSE(AS.SetTriple("unknown-unknown-unknown"));

  AS = ArchSpec();
  EXPECT_FALSE(AS.SetTriple("unknown"));

  AS = ArchSpec();
  EXPECT_FALSE(AS.SetTriple(""));
}

TEST(ArchSpecTest, MergeFrom) {
  ArchSpec A;
  ArchSpec B("x86_64-pc-linux");

  EXPECT_FALSE(A.IsValid());
  ASSERT_TRUE(B.IsValid());
  EXPECT_EQ(llvm::Triple::ArchType::x86_64, B.GetTriple().getArch());
  EXPECT_EQ(llvm::Triple::VendorType::PC, B.GetTriple().getVendor());
  EXPECT_EQ(llvm::Triple::OSType::Linux, B.GetTriple().getOS());
  EXPECT_EQ(ArchSpec::eCore_x86_64_x86_64, B.GetCore());

  A.MergeFrom(B);
  ASSERT_TRUE(A.IsValid());
  EXPECT_EQ(llvm::Triple::ArchType::x86_64, A.GetTriple().getArch());
  EXPECT_EQ(llvm::Triple::VendorType::PC, A.GetTriple().getVendor());
  EXPECT_EQ(llvm::Triple::OSType::Linux, A.GetTriple().getOS());
  EXPECT_EQ(ArchSpec::eCore_x86_64_x86_64, A.GetCore());
}

TEST(ArchSpecTest, MergeFromMachOUnknown) {
  class MyArchSpec : public ArchSpec {
  public:
    MyArchSpec() {
      this->SetTriple("unknown-mach-64");
      this->m_core = ArchSpec::eCore_uknownMach64;
      this->m_byte_order = eByteOrderLittle;
      this->m_flags = 0;
    }
  };

  MyArchSpec A;
  ASSERT_TRUE(A.IsValid());
  MyArchSpec B;
  ASSERT_TRUE(B.IsValid());
  A.MergeFrom(B);
  ASSERT_EQ(A.GetCore(), ArchSpec::eCore_uknownMach64);
}

TEST(ArchSpecTest, Compatibility) {
  {
    ArchSpec A("x86_64-apple-macosx10.12");
    ArchSpec B("x86_64-apple-macosx10.12");
    ASSERT_TRUE(A.IsExactMatch(B));
    ASSERT_TRUE(A.IsCompatibleMatch(B));
  }
  {
    // The version information is auxiliary to support availablity but
    // doesn't affect compatibility.
    ArchSpec A("x86_64-apple-macosx10.11");
    ArchSpec B("x86_64-apple-macosx10.12");
    ASSERT_TRUE(A.IsExactMatch(B));
    ASSERT_TRUE(A.IsCompatibleMatch(B));
  }
  {
    ArchSpec A("x86_64-apple-macosx10.13");
    ArchSpec B("x86_64h-apple-macosx10.13");
    ASSERT_FALSE(A.IsExactMatch(B));
    ASSERT_TRUE(A.IsCompatibleMatch(B));
  }
  {
    ArchSpec A("x86_64-apple-macosx");
    ArchSpec B("x86_64-apple-ios-simulator");
    ASSERT_FALSE(A.IsExactMatch(B));
    ASSERT_FALSE(A.IsCompatibleMatch(B));
  }
  {
    ArchSpec A("x86_64-*-*");
    ArchSpec B("x86_64-apple-ios-simulator");
    ASSERT_FALSE(A.IsExactMatch(B));
    ASSERT_FALSE(A.IsCompatibleMatch(B));
  }
  {
    ArchSpec A("arm64-*-*");
    ArchSpec B("arm64-apple-ios");
    ASSERT_FALSE(A.IsExactMatch(B));
    // FIXME: This looks unintuitive and we should investigate whether
    // this is the desired behavior.
    ASSERT_FALSE(A.IsCompatibleMatch(B));
  }
  {
    ArchSpec A("x86_64-*-*");
    ArchSpec B("x86_64-apple-ios-simulator");
    ASSERT_FALSE(A.IsExactMatch(B));
    // FIXME: See above, though the extra environment complicates things.
    ASSERT_FALSE(A.IsCompatibleMatch(B));
  }
  {
    ArchSpec A("x86_64");
    ArchSpec B("x86_64-apple-macosx10.14");
    // FIXME: The exact match also looks unintuitive.
    ASSERT_TRUE(A.IsExactMatch(B));
    ASSERT_TRUE(A.IsCompatibleMatch(B));
  }
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <unotools/closeveto.hxx>

#include <com/sun/star/util/XCloseable.hpp>

#include <cppuhelper/implbase1.hxx>
#include <rtl/ref.hxx>
#include <tools/diagnose_ex.h>

//......................................................................................................................
namespace utl
{
//......................................................................................................................

    using ::com::sun::star::uno::Reference;
    using ::com::sun::star::uno::XInterface;
    using ::com::sun::star::uno::UNO_QUERY;
    using ::com::sun::star::uno::UNO_QUERY_THROW;
    using ::com::sun::star::uno::UNO_SET_THROW;
    using ::com::sun::star::uno::Exception;
    using ::com::sun::star::uno::RuntimeException;
    using ::com::sun::star::uno::Any;
    using ::com::sun::star::uno::makeAny;
    using ::com::sun::star::uno::Sequence;
    using ::com::sun::star::uno::Type;
    using ::com::sun::star::util::XCloseable;
    using ::com::sun::star::util::XCloseListener;
    using ::com::sun::star::util::CloseVetoException;
    using ::com::sun::star::lang::EventObject;

    //==================================================================================================================
    //= CloseListener_Impl
    //==================================================================================================================
    typedef ::cppu::WeakImplHelper1 <   XCloseListener
                                    >   CloseListener_Base;
    class SAL_DLLPRIVATE CloseListener_Impl : public CloseListener_Base
    {
    public:
        CloseListener_Impl()
            :m_bHasOwnership( false )
        {
        }

        // XCloseListener
        virtual void SAL_CALL queryClosing( const EventObject& Source, ::sal_Bool GetsOwnership ) throw (CloseVetoException, RuntimeException);
        virtual void SAL_CALL notifyClosing( const EventObject& Source ) throw (RuntimeException);

        // XEventListener
        virtual void SAL_CALL disposing( const EventObject& Source) throw (RuntimeException);

        bool hasOwnership() const { return m_bHasOwnership; }

    protected:
        ~CloseListener_Impl()
        {
        }

    private:
        bool    m_bHasOwnership;
    };

    //------------------------------------------------------------------------------------------------------------------
    void SAL_CALL CloseListener_Impl::queryClosing( const EventObject& i_source, ::sal_Bool i_deliverOwnership ) throw (CloseVetoException, RuntimeException)
    {
        (void)i_source;

        if ( !m_bHasOwnership )
            m_bHasOwnership = i_deliverOwnership;

        throw CloseVetoException();
    }

    //------------------------------------------------------------------------------------------------------------------
    void SAL_CALL CloseListener_Impl::notifyClosing( const EventObject& i_source ) throw (RuntimeException)
    {
        (void)i_source;
    }

    //------------------------------------------------------------------------------------------------------------------
    void SAL_CALL CloseListener_Impl::disposing( const EventObject& i_source ) throw (RuntimeException)
    {
        (void)i_source;
    }

    //==================================================================================================================
    //= CloseVeto_Data
    //==================================================================================================================
    struct SAL_DLLPRIVATE CloseVeto_Data
    {
        Reference< XCloseable >                 xCloseable;
        ::rtl::Reference< CloseListener_Impl >  pListener;
    };

    //==================================================================================================================
    //= operations
    //==================================================================================================================
    namespace
    {
        //--------------------------------------------------------------------------------------------------------------
        void lcl_init( CloseVeto_Data& i_data, const Reference< XInterface >& i_closeable )
        {
            i_data.xCloseable.set( i_closeable, UNO_QUERY );
            ENSURE_OR_RETURN_VOID( i_data.xCloseable.is(), "CloseVeto: the component is not closeable!" );

            i_data.pListener = new CloseListener_Impl;
            i_data.xCloseable->addCloseListener( i_data.pListener.get() );
        }

        //--------------------------------------------------------------------------------------------------------------
        void lcl_deinit( CloseVeto_Data& i_data )
        {
            if ( !i_data.xCloseable.is() )
                return;

            i_data.xCloseable->removeCloseListener( i_data.pListener.get() );
            if ( i_data.pListener->hasOwnership() )
            {
                try
                {
                    i_data.xCloseable->close( sal_True );
                }
                catch( const CloseVetoException& ) { }
                catch( const Exception& )
                {
                    DBG_UNHANDLED_EXCEPTION();
                }
            }
        }
    }

    //==================================================================================================================
    //= CloseVeto
    //==================================================================================================================
    //------------------------------------------------------------------------------------------------------------------
    CloseVeto::CloseVeto( const Reference< XInterface >& i_closeable )
        :m_pData( new CloseVeto_Data )
    {
        lcl_init( *m_pData, i_closeable );
    }

    //------------------------------------------------------------------------------------------------------------------
    CloseVeto::~CloseVeto()
    {
        lcl_deinit( *m_pData );
    }

//......................................................................................................................
} // namespace utl
//......................................................................................................................

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Remove needless SAL_DLLPRIVATE annotations<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <unotools/closeveto.hxx>

#include <com/sun/star/util/XCloseable.hpp>

#include <cppuhelper/implbase1.hxx>
#include <rtl/ref.hxx>
#include <tools/diagnose_ex.h>

//......................................................................................................................
namespace utl
{
//......................................................................................................................

    using ::com::sun::star::uno::Reference;
    using ::com::sun::star::uno::XInterface;
    using ::com::sun::star::uno::UNO_QUERY;
    using ::com::sun::star::uno::UNO_QUERY_THROW;
    using ::com::sun::star::uno::UNO_SET_THROW;
    using ::com::sun::star::uno::Exception;
    using ::com::sun::star::uno::RuntimeException;
    using ::com::sun::star::uno::Any;
    using ::com::sun::star::uno::makeAny;
    using ::com::sun::star::uno::Sequence;
    using ::com::sun::star::uno::Type;
    using ::com::sun::star::util::XCloseable;
    using ::com::sun::star::util::XCloseListener;
    using ::com::sun::star::util::CloseVetoException;
    using ::com::sun::star::lang::EventObject;

    //==================================================================================================================
    //= CloseListener_Impl
    //==================================================================================================================
    typedef ::cppu::WeakImplHelper1 <   XCloseListener
                                    >   CloseListener_Base;
    class CloseListener_Impl : public CloseListener_Base
    {
    public:
        CloseListener_Impl()
            :m_bHasOwnership( false )
        {
        }

        // XCloseListener
        virtual void SAL_CALL queryClosing( const EventObject& Source, ::sal_Bool GetsOwnership ) throw (CloseVetoException, RuntimeException);
        virtual void SAL_CALL notifyClosing( const EventObject& Source ) throw (RuntimeException);

        // XEventListener
        virtual void SAL_CALL disposing( const EventObject& Source) throw (RuntimeException);

        bool hasOwnership() const { return m_bHasOwnership; }

    protected:
        ~CloseListener_Impl()
        {
        }

    private:
        bool    m_bHasOwnership;
    };

    //------------------------------------------------------------------------------------------------------------------
    void SAL_CALL CloseListener_Impl::queryClosing( const EventObject& i_source, ::sal_Bool i_deliverOwnership ) throw (CloseVetoException, RuntimeException)
    {
        (void)i_source;

        if ( !m_bHasOwnership )
            m_bHasOwnership = i_deliverOwnership;

        throw CloseVetoException();
    }

    //------------------------------------------------------------------------------------------------------------------
    void SAL_CALL CloseListener_Impl::notifyClosing( const EventObject& i_source ) throw (RuntimeException)
    {
        (void)i_source;
    }

    //------------------------------------------------------------------------------------------------------------------
    void SAL_CALL CloseListener_Impl::disposing( const EventObject& i_source ) throw (RuntimeException)
    {
        (void)i_source;
    }

    //==================================================================================================================
    //= CloseVeto_Data
    //==================================================================================================================
    struct CloseVeto_Data
    {
        Reference< XCloseable >                 xCloseable;
        ::rtl::Reference< CloseListener_Impl >  pListener;
    };

    //==================================================================================================================
    //= operations
    //==================================================================================================================
    namespace
    {
        //--------------------------------------------------------------------------------------------------------------
        void lcl_init( CloseVeto_Data& i_data, const Reference< XInterface >& i_closeable )
        {
            i_data.xCloseable.set( i_closeable, UNO_QUERY );
            ENSURE_OR_RETURN_VOID( i_data.xCloseable.is(), "CloseVeto: the component is not closeable!" );

            i_data.pListener = new CloseListener_Impl;
            i_data.xCloseable->addCloseListener( i_data.pListener.get() );
        }

        //--------------------------------------------------------------------------------------------------------------
        void lcl_deinit( CloseVeto_Data& i_data )
        {
            if ( !i_data.xCloseable.is() )
                return;

            i_data.xCloseable->removeCloseListener( i_data.pListener.get() );
            if ( i_data.pListener->hasOwnership() )
            {
                try
                {
                    i_data.xCloseable->close( sal_True );
                }
                catch( const CloseVetoException& ) { }
                catch( const Exception& )
                {
                    DBG_UNHANDLED_EXCEPTION();
                }
            }
        }
    }

    //==================================================================================================================
    //= CloseVeto
    //==================================================================================================================
    //------------------------------------------------------------------------------------------------------------------
    CloseVeto::CloseVeto( const Reference< XInterface >& i_closeable )
        :m_pData( new CloseVeto_Data )
    {
        lcl_init( *m_pData, i_closeable );
    }

    //------------------------------------------------------------------------------------------------------------------
    CloseVeto::~CloseVeto()
    {
        lcl_deinit( *m_pData );
    }

//......................................................................................................................
} // namespace utl
//......................................................................................................................

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>#include "iostream"

// --- Custom header files ---
#include "AliAnalysisTaskPP13.h"
#include <AliPP13AnalysisCluster.h>
#include <AliPP13TriggerProperties.h>

// --- ROOT header files ---
#include <TFile.h>
#include <TObjArray.h>
#include <TROOT.h>

// --- AliRoot header files ---
#include "AliAnalysisManager.h"
#include <AliVEvent.h>
#include <AliVCaloCells.h>
#include <AliVCluster.h>
#include <AliAODCaloCluster.h>
#include <AliVVertex.h>
#include <AliPHOSGeometry.h>
#include <AliLog.h>
#include <AliAODMCParticle.h>
#include <AliAODEvent.h>
#include "AliPHOSTriggerUtils.h"

// --- AliRoot MC headers ---
#include <AliMCEventHandler.h>
#include <AliMCEvent.h>

ClassImp(AliAnalysisTaskPP13)

//________________________________________________________________
AliAnalysisTaskPP13::AliAnalysisTaskPP13() : AliAnalysisTaskSE(),
	fPreviousEvents(0),
	fSelections(0),
	fNMixedEvents(0)
{
	// Constructor for root I/O, do not use it
}

//________________________________________________________________
AliAnalysisTaskPP13::AliAnalysisTaskPP13(const char * name, TList * selections, Int_t nmix):
	AliAnalysisTaskSE(name),
	fPreviousEvents(0),
	fSelections(selections),
	fNMixedEvents(nmix)
{
	fSelections->SetOwner(kTRUE);

	for (int i = 0; i < fSelections->GetEntries(); ++i)
		DefineOutput(i + 1, TList::Class()); // Output starts from 1
}

//________________________________________________________________
AliAnalysisTaskPP13::~AliAnalysisTaskPP13()
{
	if (!AliAnalysisManager::GetAnalysisManager()->IsProofMode()) delete fSelections;
	if (fPreviousEvents) delete fPreviousEvents;
}

//________________________________________________________________
void AliAnalysisTaskPP13::UserCreateOutputObjects()
{
	// Initialization of all outputs
	for (int i = 0; i < fSelections->GetEntries(); ++i)
	{
		AliPP13PhysicsSelection * selection = dynamic_cast<AliPP13PhysicsSelection *> (fSelections->At(i));
		selection->InitSummaryHistograms();
		PostData(i + 1, selection->GetListOfHistos()); // Output starts from 1
	}

	fPreviousEvents = new AliPP13MixingSample(fNMixedEvents);
}

//________________________________________________________________
void AliAnalysisTaskPP13::UserExec(Option_t *)
{
	// Does the job for one event

	// event
	AliVEvent * event = InputEvent();
	if (!event)
	{
		AliWarning("Can't get event");
		return;
	}

	AliPHOSTriggerUtils * triggerUtils = new AliPHOSTriggerUtils("PHOSTrig");
	triggerUtils->SetEvent(event);

    AliPP13TriggerProperties triggerProperties(
    	event->GetCaloTrigger("PHOS")
    );

	// Count MB event before event cuts for every selection
	for (int i = 0; i < fSelections->GetEntries(); ++i)
	{
		AliPP13PhysicsSelection * selection = dynamic_cast<AliPP13PhysicsSelection *> (fSelections->At(i));
		selection->CountMBEvent();
	}

	// check geometry
	if (!AliPHOSGeometry::GetInstance())
	{
		AliInfo("PHOS geometry not initialized, initializing it for you");
		// Don't instantinate geometry: Use tender
		AliPHOSGeometry::GetInstance();
	}

	// Select Event
	EventFlags evtProperties;
	if (!EventSelected(event, evtProperties))
		return;

	// Set the Event handler if it's available
	AliAnalysisManager * manager = AliAnalysisManager::GetAnalysisManager();
	if (manager)
	{
		AliInputEventHandler * inputHandler = dynamic_cast<AliInputEventHandler * >(manager->GetInputEventHandler());
		if (inputHandler)
			evtProperties.fPIDResponse = inputHandler->GetPIDResponse();
	}

	// NB: Use don't use TClonesArray as you don't want to copy the clusters
	// just use pointers
	//
	Int_t nTriggered = 0;
	TObjArray clusArray;
	clusArray.SetOwner(kTRUE);
	for (Int_t i = 0; i < event->GetNumberOfCaloClusters(); i++)
	{
		AliAODCaloCluster * c = dynamic_cast<AliAODCaloCluster *> (event->GetCaloCluster(i));
		if (!c)
		{
			AliWarning("Can't get cluster");
			return;
		}

		AliPP13AnalysisCluster * clus = new AliPP13AnalysisCluster(*c);

		if (!clus->IsPHOS())
			continue;

		triggerProperties.FillTriggerInformation(clus);
		clus->SetTrigger(triggerUtils->IsFiredTrigger(c));
		nTriggered += clus->IsTrigger();

		clusArray.Add(clus);
	}
	delete triggerUtils;

	evtProperties.fTriggerEvent = nTriggered > 0;
	evtProperties.fMcParticles = GetMCParticles(event);

	TList * pool = fPreviousEvents->GetPool(evtProperties);
	for (int i = 0; i < fSelections->GetEntries(); ++i) // Fill and Post Data to outputs
	{
		AliPP13PhysicsSelection * selection = dynamic_cast<AliPP13PhysicsSelection *> (fSelections->At(i));

		if (!selection->SelectEvent(evtProperties))
			continue;

		selection->FillHistograms(&clusArray, pool, evtProperties);
		selection->ConsiderGeneratedParticles(evtProperties);

		PostData(i + 1, selection->GetListOfHistos()); // Output starts from 1
	}
	fPreviousEvents->UpdatePool(clusArray, evtProperties);
}

//________________________________________________________________
TClonesArray * AliAnalysisTaskPP13::GetMCParticles(const AliVEvent * event) const
{
	const AliAODEvent * aodevent = dynamic_cast<const AliAODEvent*>(event);

	if (!aodevent)
		return 0;

	TClonesArray * mc = (TClonesArray*)aodevent->FindListObject(AliAODMCParticle::StdBranchName());
	return mc;
}

//________________________________________________________________
void AliAnalysisTaskPP13::Terminate(Option_t *)
{
}

//________________________________________________________________
Bool_t AliAnalysisTaskPP13::EventSelected(const AliVEvent * event, EventFlags & eprops) const
{
	// pileup
	if (event->IsPileupFromSPD(3, 0.8, 3., 2., 5.))
		return kFALSE;

	// TODO: DO we need this check?
	// cells
	AliVCaloCells * cells = event->GetPHOSCells();

	if (!cells)
	{
		AliWarning("Can't get cells");
		return kFALSE;
	}

	// primary vertex
	AliVVertex * vertex = (AliVVertex *) event->GetPrimaryVertex();
	if (!vertex)
	{
		AliWarning("Can't get primary vertex");
		return kFALSE;
	}

	vertex->GetXYZ(eprops.vtxBest);
	eprops.BC = event->GetBunchCrossNumber();

	eprops.ncontributors = vertex->GetNContributors();

	return kTRUE;
}
<commit_msg>Remove trigger utils as it to reduce memory consumption<commit_after>#include "iostream"

// --- Custom header files ---
#include "AliAnalysisTaskPP13.h"
#include <AliPP13AnalysisCluster.h>
#include <AliPP13TriggerProperties.h>

// --- ROOT header files ---
#include <TFile.h>
#include <TObjArray.h>
#include <TROOT.h>

// --- AliRoot header files ---
#include "AliAnalysisManager.h"
#include <AliVEvent.h>
#include <AliVCaloCells.h>
#include <AliVCluster.h>
#include <AliAODCaloCluster.h>
#include <AliVVertex.h>
#include <AliPHOSGeometry.h>
#include <AliLog.h>
#include <AliAODMCParticle.h>
#include <AliAODEvent.h>
#include "AliPHOSTriggerUtils.h"

// --- AliRoot MC headers ---
#include <AliMCEventHandler.h>
#include <AliMCEvent.h>

ClassImp(AliAnalysisTaskPP13)

//________________________________________________________________
AliAnalysisTaskPP13::AliAnalysisTaskPP13() : AliAnalysisTaskSE(),
	fPreviousEvents(0),
	fSelections(0),
	fNMixedEvents(0)
{
	// Constructor for root I/O, do not use it
}

//________________________________________________________________
AliAnalysisTaskPP13::AliAnalysisTaskPP13(const char * name, TList * selections, Int_t nmix):
	AliAnalysisTaskSE(name),
	fPreviousEvents(0),
	fSelections(selections),
	fNMixedEvents(nmix)
{
	fSelections->SetOwner(kTRUE);

	for (int i = 0; i < fSelections->GetEntries(); ++i)
		DefineOutput(i + 1, TList::Class()); // Output starts from 1
}

//________________________________________________________________
AliAnalysisTaskPP13::~AliAnalysisTaskPP13()
{
	if (!AliAnalysisManager::GetAnalysisManager()->IsProofMode()) delete fSelections;
	if (fPreviousEvents) delete fPreviousEvents;
}

//________________________________________________________________
void AliAnalysisTaskPP13::UserCreateOutputObjects()
{
	// Initialization of all outputs
	for (int i = 0; i < fSelections->GetEntries(); ++i)
	{
		AliPP13PhysicsSelection * selection = dynamic_cast<AliPP13PhysicsSelection *> (fSelections->At(i));
		selection->InitSummaryHistograms();
		PostData(i + 1, selection->GetListOfHistos()); // Output starts from 1
	}

	fPreviousEvents = new AliPP13MixingSample(fNMixedEvents);
}

//________________________________________________________________
void AliAnalysisTaskPP13::UserExec(Option_t *)
{
	// Does the job for one event

	// event
	AliVEvent * event = InputEvent();
	if (!event)
	{
		AliWarning("Can't get event");
		return;
	}

	// AliPHOSTriggerUtils * triggerUtils = new AliPHOSTriggerUtils("PHOSTrig");
	// triggerUtils->SetEvent(event);

	AliPP13TriggerProperties triggerProperties(
		event->GetCaloTrigger("PHOS")
	);

	// Count MB event before event cuts for every selection
	for (int i = 0; i < fSelections->GetEntries(); ++i)
	{
		AliPP13PhysicsSelection * selection = dynamic_cast<AliPP13PhysicsSelection *> (fSelections->At(i));
		selection->CountMBEvent();
	}

	// check geometry
	if (!AliPHOSGeometry::GetInstance())
	{
		AliInfo("PHOS geometry not initialized, initializing it for you");
		// Don't instantinate geometry: Use tender
		AliPHOSGeometry::GetInstance();
	}

	// Select Event
	EventFlags evtProperties;
	if (!EventSelected(event, evtProperties))
		return;

	// Set the Event handler if it's available
	AliAnalysisManager * manager = AliAnalysisManager::GetAnalysisManager();
	if (manager)
	{
		AliInputEventHandler * inputHandler = dynamic_cast<AliInputEventHandler * >(manager->GetInputEventHandler());
		if (inputHandler)
			evtProperties.fPIDResponse = inputHandler->GetPIDResponse();
	}

	// NB: Use don't use TClonesArray as you don't want to copy the clusters
	// just use pointers
	//
	Int_t nTriggered = 0;
	TObjArray clusArray;
	// clusArray.SetOwner(kTRUE);
	for (Int_t i = 0; i < event->GetNumberOfCaloClusters(); i++)
	{
		AliVCluster * clus = event->GetCaloCluster(i);
		// AliAODCaloCluster * c = dynamic_cast<AliAODCaloCluster *> (event->GetCaloCluster(i));
		if (!clus)
		{
			AliWarning("Can't get cluster");
			return;
		}

		// AliPP13AnalysisCluster * clus = new AliPP13AnalysisCluster(*c);

		if (!clus->IsPHOS())
			continue;

		// triggerProperties.FillTriggerInformation(clus);
		// clus->SetTrigger(triggerUtils->IsFiredTrigger(c));
		// nTriggered += clus->IsTrigger();

		clusArray.Add(clus);
	}
	// delete triggerUtils;

	evtProperties.fTriggerEvent = nTriggered > 0;
	evtProperties.fMcParticles = GetMCParticles(event);

	TList * pool = fPreviousEvents->GetPool(evtProperties);
	for (int i = 0; i < fSelections->GetEntries(); ++i) // Fill and Post Data to outputs
	{
		AliPP13PhysicsSelection * selection = dynamic_cast<AliPP13PhysicsSelection *> (fSelections->At(i));

		if (!selection->SelectEvent(evtProperties))
			continue;

		selection->FillHistograms(&clusArray, pool, evtProperties);
		selection->ConsiderGeneratedParticles(evtProperties);

		PostData(i + 1, selection->GetListOfHistos()); // Output starts from 1
	}
	fPreviousEvents->UpdatePool(clusArray, evtProperties);
}

//________________________________________________________________
TClonesArray * AliAnalysisTaskPP13::GetMCParticles(const AliVEvent * event) const
{
	const AliAODEvent * aodevent = dynamic_cast<const AliAODEvent*>(event);

	if (!aodevent)
		return 0;

	TClonesArray * mc = (TClonesArray*)aodevent->FindListObject(AliAODMCParticle::StdBranchName());
	return mc;
}

//________________________________________________________________
void AliAnalysisTaskPP13::Terminate(Option_t *)
{
}

//________________________________________________________________
Bool_t AliAnalysisTaskPP13::EventSelected(const AliVEvent * event, EventFlags & eprops) const
{
	// pileup
	if (event->IsPileupFromSPD(3, 0.8, 3., 2., 5.))
		return kFALSE;

	// TODO: DO we need this check?
	// cells
	AliVCaloCells * cells = event->GetPHOSCells();

	if (!cells)
	{
		AliWarning("Can't get cells");
		return kFALSE;
	}

	// primary vertex
	AliVVertex * vertex = (AliVVertex *) event->GetPrimaryVertex();
	if (!vertex)
	{
		AliWarning("Can't get primary vertex");
		return kFALSE;
	}

	vertex->GetXYZ(eprops.vtxBest);
	eprops.BC = event->GetBunchCrossNumber();

	eprops.ncontributors = vertex->GetNContributors();

	return kTRUE;
}
<|endoftext|>


<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.

#include "TestFeature.hpp"

#include <nix/util/util.hpp>
#include <nix/valid/validate.hpp>

#include <sstream>
#include <ctime>

using namespace std;
using namespace nix;
using namespace valid;

void TestFeature::setUp() {
    file = File::open("test_feature.h5", FileMode::Overwrite);
    block = file.createBlock("featureTest","test");

    data_array = block.createDataArray("featureTest", "Test",
                                       DataType::Double, nix::NDSize({ 0 }));

    tag = block.createTag("featureTest", "Test", {0.0, 2.0, 3.4});
}

void TestFeature::tearDown() {
    file.deleteBlock(block.id());
    file.close();
}

void TestFeature::testValidate() {
    Feature rp = tag.createFeature(data_array, nix::LinkType::Tagged);

    valid::Result result = validate(rp);
    CPPUNIT_ASSERT(result.getErrors().size() == 0);
    CPPUNIT_ASSERT(result.getWarnings().size() == 0);
}

void TestFeature::testId() {
    Feature rp = tag.createFeature(data_array, nix::LinkType::Tagged);
    CPPUNIT_ASSERT(rp.id().size() == 36);
    tag.deleteFeature(rp.id());
}

void TestFeature::testLinkType(){
    Feature rp = tag.createFeature(data_array, nix::LinkType::Tagged);
    CPPUNIT_ASSERT(rp.linkType() == nix::LinkType::Tagged);
    rp.linkType(nix::LinkType::Untagged);

    CPPUNIT_ASSERT(rp.linkType() == nix::LinkType::Untagged);
    rp.linkType(nix::LinkType::Tagged);
    CPPUNIT_ASSERT(rp.linkType() == nix::LinkType::Tagged);

    rp.linkType(nix::LinkType::Indexed);
    CPPUNIT_ASSERT(rp.linkType() == nix::LinkType::Indexed);

    tag.deleteFeature(rp.id());
}

void TestFeature::testData() {
    Feature rp = tag.createFeature(data_array, nix::LinkType::Tagged);
    DataArray da_2 = block.createDataArray("array2", "Test",
                                           DataType::Double, nix::NDSize({ 0 }));
    CPPUNIT_ASSERT(rp.data().id() == data_array.id());
    rp.data(da_2);
    CPPUNIT_ASSERT(rp.data().id() == da_2.id());
    block.deleteDataArray(da_2.id());
    // make sure link is gone with deleted data array
    CPPUNIT_ASSERT_THROW(rp.data(), std::runtime_error);
    tag.deleteFeature(rp.id());
}

void TestFeature::testLinkType2Str() {
    CPPUNIT_ASSERT(link_type_to_string(nix::LinkType::Tagged) == "Tagged");
    CPPUNIT_ASSERT(link_type_to_string(nix::LinkType::Untagged) == "Untagged");
    CPPUNIT_ASSERT(link_type_to_string(nix::LinkType::Indexed) == "Indexed");
}

void TestFeature::testStreamOperator() {
    stringstream s1, s2, s3;
    s1 << nix::LinkType::Indexed;
    CPPUNIT_ASSERT(s1.str() == "LinkType::Indexed");
    s2 << nix::LinkType::Tagged;
    CPPUNIT_ASSERT(s2.str() == "LinkType::Tagged");
    s3 << nix::LinkType::Untagged;
    CPPUNIT_ASSERT(s3.str() == "LinkType::Untagged");
}

void TestFeature::testOperator() {
    Feature rp = tag.createFeature(data_array, nix::LinkType::Tagged);

    CPPUNIT_ASSERT(rp != none);
    rp = none;
    CPPUNIT_ASSERT(rp == false);
    CPPUNIT_ASSERT(rp == none);
}
<commit_msg>[testFeature] extended test to check for exceptions<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.

#include "TestFeature.hpp"

#include <nix/util/util.hpp>
#include <nix/valid/validate.hpp>

#include <sstream>
#include <ctime>

using namespace std;
using namespace nix;
using namespace valid;

void TestFeature::setUp() {
    file = File::open("test_feature.h5", FileMode::Overwrite);
    block = file.createBlock("featureTest","test");

    data_array = block.createDataArray("featureTest", "Test",
                                       DataType::Double, nix::NDSize({ 0 }));

    tag = block.createTag("featureTest", "Test", {0.0, 2.0, 3.4});
}

void TestFeature::tearDown() {
    file.deleteBlock(block.id());
    file.close();
}

void TestFeature::testValidate() {
    Feature rp = tag.createFeature(data_array, nix::LinkType::Tagged);

    valid::Result result = validate(rp);
    CPPUNIT_ASSERT(result.getErrors().size() == 0);
    CPPUNIT_ASSERT(result.getWarnings().size() == 0);
}

void TestFeature::testId() {
    Feature rp = tag.createFeature(data_array, nix::LinkType::Tagged);
    CPPUNIT_ASSERT(rp.id().size() == 36);
    tag.deleteFeature(rp.id());
}

void TestFeature::testLinkType(){
    Feature rp = tag.createFeature(data_array, nix::LinkType::Tagged);
    CPPUNIT_ASSERT(rp.linkType() == nix::LinkType::Tagged);
    rp.linkType(nix::LinkType::Untagged);

    CPPUNIT_ASSERT(rp.linkType() == nix::LinkType::Untagged);
    rp.linkType(nix::LinkType::Tagged);
    CPPUNIT_ASSERT(rp.linkType() == nix::LinkType::Tagged);

    rp.linkType(nix::LinkType::Indexed);
    CPPUNIT_ASSERT(rp.linkType() == nix::LinkType::Indexed);

    tag.deleteFeature(rp.id());
}

void TestFeature::testData() {
    DataArray a;
    Feature f;
    CPPUNIT_ASSERT_THROW(tag.createFeature(a, nix::LinkType::Tagged), std::runtime_error);
    CPPUNIT_ASSERT_THROW(f.data(a), std::runtime_error);
    Feature rp = tag.createFeature(data_array, nix::LinkType::Tagged);
    DataArray da_2 = block.createDataArray("array2", "Test",
                                           DataType::Double, nix::NDSize({ 0 }));
    CPPUNIT_ASSERT(rp.data().id() == data_array.id());
    rp.data(da_2);
    CPPUNIT_ASSERT(rp.data().id() == da_2.id());
    block.deleteDataArray(da_2.id());
    // make sure link is gone with deleted data array
    CPPUNIT_ASSERT_THROW(rp.data(), std::runtime_error);
    tag.deleteFeature(rp.id());
}

void TestFeature::testLinkType2Str() {
    CPPUNIT_ASSERT(link_type_to_string(nix::LinkType::Tagged) == "Tagged");
    CPPUNIT_ASSERT(link_type_to_string(nix::LinkType::Untagged) == "Untagged");
    CPPUNIT_ASSERT(link_type_to_string(nix::LinkType::Indexed) == "Indexed");
}

void TestFeature::testStreamOperator() {
    stringstream s1, s2, s3;
    s1 << nix::LinkType::Indexed;
    CPPUNIT_ASSERT(s1.str() == "LinkType::Indexed");
    s2 << nix::LinkType::Tagged;
    CPPUNIT_ASSERT(s2.str() == "LinkType::Tagged");
    s3 << nix::LinkType::Untagged;
    CPPUNIT_ASSERT(s3.str() == "LinkType::Untagged");
}

void TestFeature::testOperator() {
    Feature rp = tag.createFeature(data_array, nix::LinkType::Tagged);

    CPPUNIT_ASSERT(rp != none);
    rp = none;
    CPPUNIT_ASSERT(rp == false);
    CPPUNIT_ASSERT(rp == none);
}
<|endoftext|>