repo_id
stringlengths
21
96
file_path
stringlengths
31
155
content
stringlengths
1
92.9M
__index_level_0__
int64
0
0
rapidsai_public_repos/code-share/maxflow/galois
rapidsai_public_repos/code-share/maxflow/galois/src/PreAlloc.cpp
/** Implementation for pre allocation feature -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2013, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author Andrew Lenharth <[email protected]> */ #include "Galois/Runtime/ParallelWork.h" void Galois::Runtime::preAlloc_impl(int num) { int a = activeThreads; a = (num + a - 1) / a; RunCommand w[2] = {std::bind(Galois::Runtime::MM::pagePreAlloc, a), std::ref(getSystemBarrier())}; getSystemThreadPool().run(&w[0], &w[2], activeThreads); }
0
rapidsai_public_repos/code-share/maxflow/galois
rapidsai_public_repos/code-share/maxflow/galois/src/PerThreadStorage.cpp
/** Per Thread Storage -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2013, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author Andrew Lenharth <[email protected]> */ #include "Galois/Runtime/PerThreadStorage.h" #include "Galois/Runtime/ll/gio.h" #include "Galois/Runtime/mm/Mem.h" __thread char* Galois::Runtime::ptsBase; Galois::Runtime::PerBackend& Galois::Runtime::getPTSBackend() { static Galois::Runtime::PerBackend b; return b; } __thread char* Galois::Runtime::ppsBase; Galois::Runtime::PerBackend& Galois::Runtime::getPPSBackend() { static Galois::Runtime::PerBackend b; return b; } #define MORE_MEM_HACK #ifdef MORE_MEM_HACK const size_t allocSize = Galois::Runtime::MM::pageSize * 10; inline void* alloc() { return malloc(allocSize); } #else const size_t allocSize = Galois::Runtime::MM::pageSize; inline void* alloc() { return Galois::Runtime::MM::pageAlloc(); } #endif #undef MORE_MEM_HACK unsigned Galois::Runtime::PerBackend::nextLog2(unsigned size) { unsigned i = MIN_SIZE; while ((1<<i) < size) { ++i; } if (i >= MAX_SIZE) { GALOIS_DIE ("PTS size too big"); } return i; } unsigned Galois::Runtime::PerBackend::allocOffset(const unsigned sz) { unsigned retval = allocSize; unsigned size = (1 << nextLog2(sz)); if ((nextLoc + size) <= allocSize) { // simple path, where we allocate bump ptr style retval = __sync_fetch_and_add (&nextLoc, size); } else { // find a free offset unsigned index = nextLog2(sz); if (!freeOffsets[index].empty()) { retval = freeOffsets[index].back(); freeOffsets[index].pop_back(); } else { // find a bigger size for (; (index < MAX_SIZE) && (freeOffsets[index].empty()); ++index) ; if (index == MAX_SIZE) { GALOIS_DIE("PTS out of memory error"); } else { // Found a bigger free offset. Use the first piece equal to required // size and produce vending machine change for the rest. assert(!freeOffsets[index].empty()); retval = freeOffsets[index].back(); freeOffsets[index].pop_back(); // remaining chunk unsigned end = retval + (1 << index); unsigned start = retval + size; for (unsigned i = index - 1; start < end; --i) { freeOffsets[i].push_back(start); start += (1 << i); } } } } assert(retval != allocSize); return retval; } void Galois::Runtime::PerBackend::deallocOffset(const unsigned offset, const unsigned sz) { unsigned size = (1 << nextLog2(sz)); if (__sync_bool_compare_and_swap(&nextLoc, offset + size, offset)) { ; // allocation was at the end , so recovered some memory } else { // allocation not at the end freeOffsets[nextLog2(sz)].push_back(offset); } } void* Galois::Runtime::PerBackend::getRemote(unsigned thread, unsigned offset) { char* rbase = heads[thread]; assert(rbase); return &rbase[offset]; } void Galois::Runtime::PerBackend::initCommon() { if (heads.empty()) heads.resize(LL::getMaxThreads()); } char* Galois::Runtime::PerBackend::initPerThread() { initCommon(); char* b = heads[LL::getTID()] = (char*) alloc(); memset(b, 0, allocSize); return b; } char* Galois::Runtime::PerBackend::initPerPackage() { initCommon(); unsigned id = LL::getTID(); unsigned leader = LL::getLeaderForThread(id); if (id == leader) { char* b = heads[id] = (char*) alloc(); memset(b, 0, allocSize); return b; } else { //wait for leader to fix up package while (__sync_bool_compare_and_swap(&heads[leader], 0, 0)) { LL::asmPause(); } heads[id] = heads[leader]; return heads[id]; } } void Galois::Runtime::initPTS() { if (!Galois::Runtime::ptsBase) { //unguarded initialization as initPTS will run in the master thread //before any other threads are generated Galois::Runtime::ptsBase = getPTSBackend().initPerThread(); } if (!Galois::Runtime::ppsBase) { Galois::Runtime::ppsBase = getPPSBackend().initPerPackage(); } } #ifdef GALOIS_USE_EXP char* Galois::Runtime::PerBackend::initPerThread_cilk () { assert (heads.size () == LL::getMaxThreads ()); unsigned id = LL::getTID (); assert (heads[id] != nullptr); return heads[id]; } char* Galois::Runtime::PerBackend::initPerPackage_cilk () { assert (heads.size () == LL::getMaxThreads ()); unsigned id = LL::getTID (); assert (heads[id] != nullptr); return heads[id]; } void Galois::Runtime::initPTS_cilk () { if (!Galois::Runtime::ptsBase) { Galois::Runtime::ptsBase = getPTSBackend ().initPerThread_cilk (); } if (!Galois::Runtime::ppsBase) { Galois::Runtime::ppsBase = getPPSBackend ().initPerPackage_cilk (); } } #endif // GALOIS_USE_EXP
0
rapidsai_public_repos/code-share/maxflow/galois
rapidsai_public_repos/code-share/maxflow/galois/src/Threads.cpp
/** Implement user facing misc api -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author Andrew Lenharth <[email protected]> */ #include "Galois/Runtime/ThreadPool.h" #include "Galois/Runtime/ActiveThreads.h" #include "Galois/Threads.h" #include <algorithm> unsigned int Galois::Runtime::activeThreads = 1; unsigned int Galois::setActiveThreads(unsigned int num) { num = std::min(num, Galois::Runtime::getSystemThreadPool().getMaxThreads()); num = std::max(num, 1U); Galois::Runtime::activeThreads = num; return num; } unsigned int Galois::getActiveThreads() { return Galois::Runtime::activeThreads; }
0
rapidsai_public_repos/code-share/maxflow/galois
rapidsai_public_repos/code-share/maxflow/galois/src/Barrier.cpp
/** Galois barrier -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2012, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @section Description * * Fast Barrier * * @author Donald Nguyen <[email protected]> * @author Andrew Lenharth <[email protected]> */ #include "Galois/Runtime/PerThreadStorage.h" #include "Galois/Runtime/Barrier.h" #include "Galois/Runtime/ActiveThreads.h" #include "Galois/Runtime/ll/CompilerSpecific.h" #include <pthread.h> #include <cstdlib> #include <cstdio> class PthreadBarrier: public Galois::Runtime::Barrier { pthread_barrier_t bar; void checkResults(int val) { if (val) { perror("PTHREADS: "); assert(0 && "PThread check"); abort(); } } public: PthreadBarrier() { //uninitialized barriers block a lot of threads to help with debugging int rc = pthread_barrier_init(&bar, 0, ~0); checkResults(rc); } PthreadBarrier(unsigned int val) { int rc = pthread_barrier_init(&bar, 0, val); checkResults(rc); } virtual ~PthreadBarrier() { int rc = pthread_barrier_destroy(&bar); checkResults(rc); } virtual void reinit(unsigned val) { int rc = pthread_barrier_destroy(&bar); checkResults(rc); rc = pthread_barrier_init(&bar, 0, val); checkResults(rc); } virtual void wait() { int rc = pthread_barrier_wait(&bar); if (rc && rc != PTHREAD_BARRIER_SERIAL_THREAD) checkResults(rc); } }; class MCSBarrier: public Galois::Runtime::Barrier { struct treenode { //vpid is Galois::Runtime::LL::getTID() volatile bool* parentpointer; //null of vpid == 0 volatile bool* childpointers[2]; bool havechild[4]; volatile bool childnotready[4]; volatile bool parentsense; bool sense; }; Galois::Runtime::PerThreadStorage<treenode> nodes; void _reinit(unsigned P) { for (unsigned i = 0; i < nodes.size(); ++i) { treenode& n = *nodes.getRemote(i); n.sense = true; n.parentsense = false; for (int j = 0; j < 4; ++j) n.childnotready[j] = n.havechild[j] = ((4*i+j+1) < P); n.parentpointer = (i == 0) ? 0 : &nodes.getRemote((i-1)/4)->childnotready[(i-1)%4]; n.childpointers[0] = ((2*i + 1) >= P) ? 0 : &nodes.getRemote(2*i+1)->parentsense; n.childpointers[1] = ((2*i + 2) >= P) ? 0 : &nodes.getRemote(2*i+2)->parentsense; } } public: MCSBarrier(unsigned P = Galois::Runtime::activeThreads) { _reinit(P); } virtual void reinit(unsigned val) { _reinit(val); } virtual void wait() { treenode& n = *nodes.getLocal(); while (n.childnotready[0] || n.childnotready[1] || n.childnotready[2] || n.childnotready[3]) { Galois::Runtime::LL::asmPause(); } for (int i = 0; i < 4; ++i) n.childnotready[i] = n.havechild[i]; if (n.parentpointer) { //FIXME: make sure the compiler doesn't do a RMW because of the as-if rule *n.parentpointer = false; while(n.parentsense != n.sense) { Galois::Runtime::LL::asmPause(); } } //signal children in wakeup tree if (n.childpointers[0]) *n.childpointers[0] = n.sense; if (n.childpointers[1]) *n.childpointers[1] = n.sense; n.sense = !n.sense; } }; class TopoBarrier : public Galois::Runtime::Barrier { struct treenode { //vpid is Galois::Runtime::LL::getTID() //package binary tree treenode* parentpointer; //null of vpid == 0 treenode* childpointers[2]; //waiting values: unsigned havechild; volatile unsigned childnotready; //signal values volatile unsigned parentsense; }; Galois::Runtime::PerPackageStorage<treenode> nodes; Galois::Runtime::PerThreadStorage<unsigned> sense; void _reinit(unsigned P) { unsigned pkgs = Galois::Runtime::LL::getMaxPackageForThread(P-1) + 1; for (unsigned i = 0; i < pkgs; ++i) { treenode& n = *nodes.getRemoteByPkg(i); n.childnotready = 0; n.havechild = 0; for (int j = 0; j < 4; ++j) { if ((4*i+j+1) < pkgs) { ++n.childnotready; ++n.havechild; } } for (unsigned j = 0; j < P; ++j) { if (Galois::Runtime::LL::getPackageForThread(j) == i && !Galois::Runtime::LL::isPackageLeader(j)) { ++n.childnotready; ++n.havechild; } } n.parentpointer = (i == 0) ? 0 : nodes.getRemoteByPkg((i-1)/4); n.childpointers[0] = ((2*i + 1) >= pkgs) ? 0 : nodes.getRemoteByPkg(2*i+1); n.childpointers[1] = ((2*i + 2) >= pkgs) ? 0 : nodes.getRemoteByPkg(2*i+2); n.parentsense = 0; } for (unsigned i = 0; i < P; ++i) *sense.getRemote(i) = 1; #if 0 for (unsigned i = 0; i < pkgs; ++i) { treenode& n = *nodes.getRemoteByPkg(i); Galois::Runtime::LL::gPrint(i, " this ", &n, " parent ", n.parentpointer, " child[0] ", n.childpointers[0], " child[1] ", n.childpointers[1], " havechild ", n.havechild, "\n"); } #endif } public: TopoBarrier(unsigned val = Galois::Runtime::activeThreads) { _reinit(val); } //not safe if any thread is in wait virtual void reinit(unsigned val) { _reinit(val); } virtual void wait() { unsigned id = Galois::Runtime::LL::getTID(); treenode& n = *nodes.getLocal(); unsigned& s = *sense.getLocal(); bool leader = Galois::Runtime::LL::isPackageLeaderForSelf(id); //completion tree if (leader) { while (n.childnotready) { Galois::Runtime::LL::asmPause(); } n.childnotready = n.havechild; if (n.parentpointer) { __sync_fetch_and_sub(&n.parentpointer->childnotready, 1); } } else { __sync_fetch_and_sub(&n.childnotready, 1); } //wait for signal if (id != 0) { while (n.parentsense != s) { Galois::Runtime::LL::asmPause(); } } //signal children in wakeup tree if (leader) { if (n.childpointers[0]) n.childpointers[0]->parentsense = s; if (n.childpointers[1]) n.childpointers[1]->parentsense = s; if (id == 0) n.parentsense = s; } ++s; } }; Galois::Runtime::Barrier::~Barrier() {} Galois::Runtime::Barrier* Galois::Runtime::createSimpleBarrier() { return new PthreadBarrier(); } Galois::Runtime::Barrier& Galois::Runtime::getSystemBarrier() { static TopoBarrier b; static unsigned num = ~0; if (activeThreads != num) { num = activeThreads; b.reinit(num); } return b; }
0
rapidsai_public_repos/code-share/maxflow/galois/src
rapidsai_public_repos/code-share/maxflow/galois/src/ll/CMakeLists.txt
set(hwtopo) if(CMAKE_SYSTEM_NAME MATCHES "Linux") set(hwtopo "Linux") elseif(CMAKE_SYSTEM_NAME MATCHES "BlueGeneQ") set(hwtopo "BlueGeneQ") elseif(CMAKE_SYSTEM_NAME MATCHES "(Solaris|SunOS)") set(hwtopo "Solaris") else() message(FATAL_ERROR "Unknown system name: ${CMAKE_SYSTEM_NAME}") endif() add_internal_library(ll EnvCheck.cpp gIO.cpp HWTopo.cpp HWTopo${hwtopo}.cpp SimpleLock.cpp TID.cpp)
0
rapidsai_public_repos/code-share/maxflow/galois/src
rapidsai_public_repos/code-share/maxflow/galois/src/ll/gIO.cpp
/** Galois IO routines -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2013, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @section Description * * IO support for galois. We use this to handle output redirection, * and common formating issues. * * @author Andrew Lenharth <[email protected]> */ #include "Galois/config.h" #include "Galois/Runtime/ll/gio.h" #include "Galois/Runtime/ll/SimpleLock.h" #include "Galois/Runtime/ll/TID.h" #include "Galois/Runtime/ll/EnvCheck.h" #include <cstdlib> #include <cstdio> #include <ctime> #include <cstring> #include <cstdarg> #include <cerrno> #include <unistd.h> #include <iostream> #include <fstream> #include <iomanip> #include GALOIS_CXX11_STD_HEADER(mutex) static void printString(bool error, bool newline, const std::string prefix, const std::string s) { static Galois::Runtime::LL::SimpleLock<true> IOLock; // if (Galois::Runtime::networkHostID == 0) { std::lock_guard<decltype(IOLock)> lock(IOLock); std::ostream& o = error ? std::cerr : std::cout; if (prefix.length()) o << prefix << ": "; o << s; if (newline) o << "\n"; // } else { // Galois::Runtime::getSystemNetworkInterface().sendAlt(0, printString, error, newline, host, prefix, s); // } } void Galois::Runtime::LL::gDebugStr(const std::string& s) { static bool skip = EnvCheck("GALOIS_DEBUG_SKIP"); if (skip) return; static const unsigned TIME_STR_SIZE = 32; char time_str[TIME_STR_SIZE]; time_t rawtime; struct tm* timeinfo; time(&rawtime); timeinfo = localtime(&rawtime); strftime(time_str, TIME_STR_SIZE, "[%H:%M:%S]", timeinfo); std::ostringstream os; os << "[" << time_str << " " << std::setw(3) << getTID() << "] " << s; if (EnvCheck("GALOIS_DEBUG_TO_FILE")) { static Galois::Runtime::LL::SimpleLock<true> dIOLock; std::lock_guard<decltype(dIOLock)> lock(dIOLock); static std::ofstream debugOut; if (!debugOut.is_open()) { char fname[] = "gdebugXXXXXX"; int fd = mkstemp(fname); close(fd); debugOut.open(fname); gInfo("Debug output going to ", fname); } debugOut << os.str() << "\n"; debugOut.flush(); } else { printString(true, true, "DEBUG", os.str()); } } void Galois::Runtime::LL::gPrintStr(const std::string& s) { printString(false, false, "", s); } void Galois::Runtime::LL::gInfoStr(const std::string& s) { printString(false, true, "INFO", s); } void Galois::Runtime::LL::gWarnStr(const std::string& s) { printString(false, true, "WARNING", s); } void Galois::Runtime::LL::gErrorStr(const std::string& s) { printString(false, true, "ERROR", s); } void Galois::Runtime::LL::gFlush() { fflush(stdout); }
0
rapidsai_public_repos/code-share/maxflow/galois/src
rapidsai_public_repos/code-share/maxflow/galois/src/ll/TID.cpp
/** Thread ID -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS SOFTWARE * AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR ANY * PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF PERFORMANCE, AND ANY * WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF DEALING OR USAGE OF TRADE. * NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH RESPECT TO THE USE OF THE * SOFTWARE OR DOCUMENTATION. Under no circumstances shall University be liable * for incidental, special, indirect, direct or consequential damages or loss of * profits, interruption of business, or related expenses which may arise from use * of Software or Documentation, including but not limited to those resulting from * defects in Software and/or Documentation, or loss or inaccuracy of data of any * kind. * * @section Description * * This contains support for thread id. See TID.h. * * @author Andrew Lenharth <[email protected]> */ #include "Galois/Runtime/ll/TID.h" #include "Galois/Runtime/ll/HWTopo.h" #include <cassert> __thread unsigned Galois::Runtime::LL::TID = 0; static unsigned nextID = 0; namespace { struct AtomicNextId { unsigned next() { return __sync_fetch_and_add(&nextID, 1); } }; typedef AtomicNextId NextId; } static NextId next; void Galois::Runtime::LL::initTID() { TID = next.next(); assert(TID < getMaxThreads()); } #ifdef GALOIS_USE_EXP void Galois::Runtime::LL::initTID_cilk () { TID = next.next () % getMaxThreads (); } #endif // GALOIS_USE_EXP
0
rapidsai_public_repos/code-share/maxflow/galois/src
rapidsai_public_repos/code-share/maxflow/galois/src/ll/HWTopoLinux.cpp
/** Machine Descriptions on Linux -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2013, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS SOFTWARE * AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR ANY * PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF PERFORMANCE, AND ANY * WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF DEALING OR USAGE OF TRADE. * NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH RESPECT TO THE USE OF THE * SOFTWARE OR DOCUMENTATION. Under no circumstances shall University be liable * for incidental, special, indirect, direct or consequential damages or loss of * profits, interruption of business, or related expenses which may arise from use * of Software or Documentation, including but not limited to those resulting from * defects in Software and/or Documentation, or loss or inaccuracy of data of any * kind. * * @section Description * * This contains descriptions of machine topologies. These describes levels in * the machine. The lowest level is a package. * * This also matches OS cpu numbering to galois thread numbering and binds threads * to processors. Threads are assigned densly in each package before the next * package. SMT hardware contexts are bound after all real cores (int x86). * * @author Andrew Lenharth <[email protected]> */ #include "Galois/Runtime/ll/HWTopo.h" #include "Galois/Runtime/ll/EnvCheck.h" #include "Galois/Runtime/ll/gio.h" #include <vector> #include <functional> #include <algorithm> #include <cassert> #include <cstdio> #include <cstring> #include <cerrno> #include <sched.h> using namespace Galois::Runtime::LL; namespace { struct cpuinfo { int proc; int physid; int sib; int coreid; int cpucores; }; static const char* sProcInfo = "/proc/cpuinfo"; static const char* sCPUSet = "/proc/self/cpuset"; static bool linuxBindToProcessor(int proc) { cpu_set_t mask; /* CPU_ZERO initializes all the bits in the mask to zero. */ CPU_ZERO( &mask ); /* CPU_SET sets only the bit corresponding to cpu. */ // void to cancel unused result warning (void)CPU_SET( proc, &mask ); /* sched_setaffinity returns 0 in success */ if( sched_setaffinity( 0, sizeof(mask), &mask ) == -1 ) { gWarn("Could not set CPU affinity for thread ", proc, "(", strerror(errno), ")"); return false; } return true; } //! Parse /proc/cpuinfo static std::vector<cpuinfo> parseCPUInfo() { std::vector<cpuinfo> vals; vals.reserve(64); FILE* f = fopen(sProcInfo, "r"); if (!f) { GALOIS_SYS_DIE("failed opening ", sProcInfo); return vals; //Shouldn't get here } const int len = 1024; char* line = (char*)malloc(len); int cur = -1; while (fgets(line, len, f)) { int num; if (sscanf(line, "processor : %d", &num) == 1) { assert(cur < num); cur = num; vals.resize(cur + 1); vals.at(cur).proc = num; } else if (sscanf(line, "physical id : %d", &num) == 1) { vals.at(cur).physid = num; } else if (sscanf(line, "siblings : %d", &num) == 1) { vals.at(cur).sib = num; } else if (sscanf(line, "core id : %d", &num) == 1) { vals.at(cur).coreid = num; } else if (sscanf(line, "cpu cores : %d", &num) == 1) { vals.at(cur).cpucores = num; } } free(line); fclose(f); return vals; } //! Returns physical ids in current cpuset std::vector<int> parseCPUSet() { std::vector<int> vals; vals.reserve(64); //PARSE: /proc/self/cpuset FILE* f = fopen(sCPUSet, "r"); if (!f) { return vals; } const int len = 1024; char* path = (char*)malloc(len); path[0] = '/'; path[1] = '\0'; if (!fgets(path, len, f)) { fclose(f); return vals; } fclose(f); if(char* t = index(path, '\n')) *t = '\0'; if (strlen(path) == 1) { free(path); return vals; } char* path2 = (char*)malloc(len); strcpy(path2, "/dev/cpuset"); strcat(path2, path); strcat(path2, "/cpus"); f = fopen(path2, "r"); if (!f) { free(path2); free(path); GALOIS_SYS_DIE("failed opening ", path2); return vals; //Shouldn't get here } //reuse path char* np = path; if (!fgets(np, len, f)) { fclose(f); return vals; } while (np && strlen(np)) { char* c = index(np, ','); if (c) { //slice string at comma (np is old string, c is next string *c = '\0'; ++c; } char* d = index(np, '-'); if (d) { //range *d = '\0'; ++d; int b = atoi(np); int e = atoi(d); while (b <= e) vals.push_back(b++); } else { //singleton vals.push_back(atoi(np)); } np = c; }; fclose(f); free(path2); free(path); return vals; } struct AutoLinuxPolicy { //number of hw supported threads unsigned numThreads, numThreadsRaw; //number of "real" processors unsigned numCores, numCoresRaw; //number of packages unsigned numPackages, numPackagesRaw; std::vector<int> packages; std::vector<int> maxPackage; std::vector<int> virtmap; std::vector<int> leaders; //! Sort in package-dense manner struct DensePackageLessThan: public std::binary_function<int,int,bool> { const std::vector<cpuinfo>& vals; DensePackageLessThan(const std::vector<cpuinfo>& v): vals(v) { } bool operator()(int a, int b) const { if (vals[a].physid < vals[b].physid) { return true; } else if (vals[a].physid == vals[b].physid) { if (vals[a].coreid < vals[b].coreid) { return true; } else if (vals[a].coreid == vals[b].coreid) { return vals[a].proc < vals[b].proc; } else { return false; } } else { return false; } } }; struct DensePackageEqual: public std::binary_function<int,int,bool> { const std::vector<cpuinfo>& vals; DensePackageEqual(const std::vector<cpuinfo>& v): vals(v) { } bool operator()(int a, int b) const { return vals[a].physid == vals[b].physid && vals[a].coreid == vals[b].coreid; } }; AutoLinuxPolicy() { std::vector<cpuinfo> vals = parseCPUInfo(); virtmap = parseCPUSet(); if (virtmap.empty()) { //1-1 mapping for non-cpuset using systems for (unsigned i = 0; i < vals.size(); ++i) virtmap.push_back(i); } if (EnvCheck("GALOIS_DEBUG_TOPO")) printRawConfiguration(vals); //Get thread count numThreadsRaw = vals.size(); numThreads = virtmap.size(); //Get package level stuff int maxrawpackage = generateRawPackageData(vals); generatePackageData(vals); //Sort by package to get package-dense mapping std::sort(virtmap.begin(), virtmap.end(), DensePackageLessThan(vals)); generateHyperthreads(vals); //Finally renumber for virtual processor numbers finalizePackageData(vals, maxrawpackage); //Get core count numCores = generateCoreData(vals); //Compute cummulative max package int p = 0; maxPackage.resize(packages.size()); for (int i = 0; i < (int)packages.size(); ++i) { p = std::max(packages[i],p); maxPackage[i] = p; } //Compute first thread in package leaders.resize(numPackages, -1); for (int i = 0; i < (int) packages.size(); ++i) if (leaders[packages[i]] == -1) leaders[packages[i]] = i; if (EnvCheck("GALOIS_DEBUG_TOPO")) printFinalConfiguration(); } void printRawConfiguration(const std::vector<cpuinfo>& vals) { for (unsigned i = 0; i < vals.size(); ++i) { const cpuinfo& p = vals[i]; gPrint("proc ", p.proc, ", physid ", p.physid, ", sib ", p.sib, ", coreid ", p.coreid, ", cpucores ", p.cpucores, "\n"); } for (unsigned i = 0; i < virtmap.size(); ++i) gPrint(", ", virtmap[i]); gPrint("\n"); } void printFinalConfiguration() { //DEBUG: PRINT Stuff gPrint("Threads: ", numThreads, ", ", numThreadsRaw, " (raw)\n"); gPrint("Cores: ", numCores, ", ", numCoresRaw, " (raw)\n"); gPrint("Packages: ", numPackages, ", ", numPackagesRaw, " (raw)\n"); for (unsigned i = 0; i < virtmap.size(); ++i) { gPrint( "T ", i, " P ", packages[i], " Tr ", virtmap[i], " L? ", ((int)i == leaders[packages[i]] ? 1 : 0)); if (i >= numCores) gPrint(" HT"); gPrint("\n"); } } void finalizePackageData(const std::vector<cpuinfo>& vals, int maxrawpackage) { std::vector<int> mapping(maxrawpackage+1); int nextval = 1; for (int i = 0; i < (int)virtmap.size(); ++i) { int x = vals[virtmap[i]].physid; if (!mapping[x]) mapping[x] = nextval++; packages.push_back(mapping[x]-1); } } unsigned generateCoreData(const std::vector<cpuinfo>& vals) { std::vector<std::pair<int, int> > cores; //first get the raw numbers for (unsigned i = 0; i < vals.size(); ++i) cores.push_back(std::make_pair(vals[i].physid, vals[i].coreid)); std::sort(cores.begin(), cores.end()); std::vector<std::pair<int,int> >::iterator it = std::unique(cores.begin(), cores.end()); numCoresRaw = std::distance(cores.begin(), it); cores.clear(); for (unsigned i = 0; i < virtmap.size(); ++i) cores.push_back(std::make_pair(vals[virtmap[i]].physid, vals[virtmap[i]].coreid)); std::sort(cores.begin(), cores.end()); it = std::unique(cores.begin(), cores.end()); return std::distance(cores.begin(), it); } void generateHyperthreads(const std::vector<cpuinfo>& vals) { //Find duplicates, which are hyperthreads, and place them at the end // annoyingly, values after tempi are unspecified for std::unique, so copy in and out instead std::vector<int> dense(numThreads); std::vector<int>::iterator it = std::unique_copy(virtmap.begin(), virtmap.end(), dense.begin(), DensePackageEqual(vals)); std::vector<bool> mask(numThreadsRaw); for (std::vector<int>::iterator ii = dense.begin(); ii < it; ++ii) mask[*ii] = true; for (std::vector<int>::iterator ii = virtmap.begin(), ei = virtmap.end(); ii < ei; ++ii) { if (!mask[*ii]) *it++ = *ii; } virtmap = dense; } void generatePackageData(const std::vector<cpuinfo>& vals) { std::vector<int> p; for (unsigned i = 0; i < virtmap.size(); ++i) p.push_back(vals[virtmap[i]].physid); std::sort(p.begin(), p.end()); std::vector<int>::iterator it = std::unique(p.begin(), p.end()); numPackages = std::distance(p.begin(), it); } int generateRawPackageData(const std::vector<cpuinfo>& vals) { std::vector<int> p; for (unsigned i = 0; i < vals.size(); ++i) p.push_back(vals[i].physid); int retval = *std::max_element(p.begin(), p.end()); std::sort(p.begin(), p.end()); std::vector<int>::iterator it = std::unique(p.begin(), p.end()); numPackagesRaw = std::distance(p.begin(), it); return retval; } }; AutoLinuxPolicy& getPolicy() { static AutoLinuxPolicy A; return A; } } //namespace bool Galois::Runtime::LL::bindThreadToProcessor(int id) { assert(id < (int)getPolicy().virtmap.size()); return linuxBindToProcessor(getPolicy().virtmap[id]); } unsigned Galois::Runtime::LL::getProcessorForThread(int id) { return getPolicy().virtmap[id]; } unsigned Galois::Runtime::LL::getMaxThreads() { return getPolicy().numThreads; } unsigned Galois::Runtime::LL::getMaxCores() { return getPolicy().numCores; } unsigned Galois::Runtime::LL::getMaxPackages() { return getPolicy().numPackages; } unsigned Galois::Runtime::LL::getPackageForThread(int id) { assert(id < (int)getPolicy().packages.size()); return getPolicy().packages[id]; } unsigned Galois::Runtime::LL::getMaxPackageForThread(int id) { assert(id < (int)getPolicy().maxPackage.size()); return getPolicy().maxPackage[id]; } bool Galois::Runtime::LL::isPackageLeader(int id) { assert(id < (int)getPolicy().packages.size()); return getPolicy().leaders[getPolicy().packages[id]] == id; } unsigned Galois::Runtime::LL::getLeaderForThread(int id) { assert(id < (int)getPolicy().packages.size()); return getPolicy().leaders[getPolicy().packages[id]]; } unsigned Galois::Runtime::LL::getLeaderForPackage(int id) { assert(id < (int)getPolicy().leaders.size()); return getPolicy().leaders[id]; }
0
rapidsai_public_repos/code-share/maxflow/galois/src
rapidsai_public_repos/code-share/maxflow/galois/src/ll/HWTopo.cpp
#include "Galois/Runtime/ll/HWTopo.h" __thread unsigned Galois::Runtime::LL::PACKAGE_ID = 0;
0
rapidsai_public_repos/code-share/maxflow/galois/src
rapidsai_public_repos/code-share/maxflow/galois/src/ll/EnvCheck.cpp
/** Enviroment Checking Code -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author Andrew Lenharth <[email protected]> */ #include "Galois/Runtime/ll/EnvCheck.h" #include <cstdlib> bool Galois::Runtime::LL::EnvCheck(const char* parm) { if (getenv(parm)) return true; return false; } bool Galois::Runtime::LL::EnvCheck(const char* parm, int& val) { char* t = getenv(parm); if (t) { val = atoi(t); return true; } return false; }
0
rapidsai_public_repos/code-share/maxflow/galois/src
rapidsai_public_repos/code-share/maxflow/galois/src/ll/SimpleLock.cpp
/** SimpleLocks -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS SOFTWARE * AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR ANY * PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF PERFORMANCE, AND ANY * WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF DEALING OR USAGE OF TRADE. * NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH RESPECT TO THE USE OF THE * SOFTWARE OR DOCUMENTATION. Under no circumstances shall University be liable * for incidental, special, indirect, direct or consequential damages or loss of * profits, interruption of business, or related expenses which may arise from use * of Software or Documentation, including but not limited to those resulting from * defects in Software and/or Documentation, or loss or inaccuracy of data of any * kind. * * @section Description * * This contains support for SimpleLock support code. * See SimpleLock.h. * See PaddedLock.h * * @author Andrew Lenharth <[email protected]> */ #include "Galois/Runtime/ll/SimpleLock.h" #include "Galois/Runtime/ll/PaddedLock.h" void Galois::Runtime::LL::LockPairOrdered(SimpleLock<true>& L1, SimpleLock<true>& L2) { assert(&L1 != &L2); if (&L1 < &L2) { L1.lock(); L2.lock(); } else { L2.lock(); L1.lock(); } } bool Galois::Runtime::LL::TryLockPairOrdered(SimpleLock<true>& L1, SimpleLock<true>& L2) { assert(&L1 != &L2); bool T1, T2; if (&L1 < &L2) { T1 = L1.try_lock(); T2 = L2.try_lock(); } else { T2 = L2.try_lock(); T1 = L1.try_lock(); } if (T1 && T2) return true; if (T1) L1.unlock(); if (T2) L2.unlock(); return false; } void Galois::Runtime::LL::UnLockPairOrdered(SimpleLock<true>& L1, SimpleLock<true>& L2) { assert(&L1 != &L2); if (&L1 < &L2) { L1.unlock(); L2.unlock(); } else { L2.unlock(); L1.unlock(); } } void Galois::Runtime::LL::LockPairOrdered(SimpleLock<false>& L1, SimpleLock<false>& L2) { } bool Galois::Runtime::LL::TryLockPairOrdered(SimpleLock<false>& L1, SimpleLock<false>& L2) { return true; } void Galois::Runtime::LL::UnLockPairOrdered(SimpleLock<false>& L1, SimpleLock<false>& L2) { } void Galois::Runtime::LL::LockPairOrdered(PaddedLock<true>& L1, PaddedLock<true>& L2) { LockPairOrdered(L1.Lock.data, L2.Lock.data); } bool Galois::Runtime::LL::TryLockPairOrdered(PaddedLock<true>& L1, PaddedLock<true>& L2) { return TryLockPairOrdered(L1.Lock.data, L2.Lock.data); } void Galois::Runtime::LL::UnLockPairOrdered(PaddedLock<true>& L1, PaddedLock<true>& L2) { UnLockPairOrdered(L1.Lock.data, L2.Lock.data); } void Galois::Runtime::LL::LockPairOrdered(PaddedLock<false>& L1, PaddedLock<false>& L2) { } bool Galois::Runtime::LL::TryLockPairOrdered(PaddedLock<false>& L1, PaddedLock<false>& L2) { return true; } void Galois::Runtime::LL::UnLockPairOrdered(PaddedLock<false>& L1, PaddedLock<false>& L2) { }
0
rapidsai_public_repos/code-share/maxflow/galois/src
rapidsai_public_repos/code-share/maxflow/galois/src/ll/HWTopoSolaris.cpp
/** Machine Descriptions on Sun -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS SOFTWARE * AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR ANY * PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF PERFORMANCE, AND ANY * WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF DEALING OR USAGE OF TRADE. * NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH RESPECT TO THE USE OF THE * SOFTWARE OR DOCUMENTATION. Under no circumstances shall University be liable * for incidental, special, indirect, direct or consequential damages or loss of * profits, interruption of business, or related expenses which may arise from use * of Software or Documentation, including but not limited to those resulting from * defects in Software and/or Documentation, or loss or inaccuracy of data of any * kind. * * @section Description * * See HWTopoLinux.cpp. * * @author Andrew Lenharth <[email protected]> */ #include "Galois/Runtime/ll/HWTopo.h" #include <vector> #include <unistd.h> #include <stdio.h> #include <thread.h> #include <sys/types.h> #include <sys/processor.h> #include <sys/procset.h> using namespace Galois::Runtime::LL; namespace { static bool sunBindToProcessor(int proc) { if (processor_bind(P_LWPID, thr_self(), proc, 0) == -1) { gWarn("Could not set CPU affinity for thread ", proc, "(", strerror(errno), ")"); return false; } return true; } //Flat machine with the correct number of threads and binding struct Policy { std::vector<int> procmap; //Galois id -> solaris id unsigned numThreads, numCores, numPackages; Policy() { processorid_t i, cpuid_max; cpuid_max = sysconf(_SC_CPUID_MAX); for (i = 0; i <= cpuid_max; i++) { if (p_online(i, P_STATUS) != -1) { procmap.push_back(i); //printf("processor %d present\n", i); } } numThreads = procmap.size(); numCores = procmap.size(); numPackages = 1; } }; Policy& getPolicy() { static Policy A; return A; } } //namespace bool Galois::Runtime::LL::bindThreadToProcessor(int id) { return sunBindToProcessor(getPolicy().procmap[id]); } unsigned Galois::Runtime::LL::getProcessorForThread(int id) { return getPolicy().procmap[id]; } unsigned Galois::Runtime::LL::getMaxThreads() { return getPolicy().numThreads; } unsigned Galois::Runtime::LL::getMaxCores() { return getPolicy().numCores; } unsigned Galois::Runtime::LL::getMaxPackages() { return getPolicy().numPackages; } unsigned Galois::Runtime::LL::getMaxPackageForThread(int id) { return getPolicy().numPackages - 1; } unsigned Galois::Runtime::LL::getPackageForThread(int id) { return 0; } bool Galois::Runtime::LL::isPackageLeader(int id) { return id == 0; }
0
rapidsai_public_repos/code-share/maxflow/galois/src
rapidsai_public_repos/code-share/maxflow/galois/src/ll/HWTopoBlueGeneQ.cpp
/** Machine Descriptions on BlueGeneQ -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2013, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS SOFTWARE * AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR ANY * PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF PERFORMANCE, AND ANY * WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF DEALING OR USAGE OF TRADE. * NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH RESPECT TO THE USE OF THE * SOFTWARE OR DOCUMENTATION. Under no circumstances shall University be liable * for incidental, special, indirect, direct or consequential damages or loss of * profits, interruption of business, or related expenses which may arise from use * of Software or Documentation, including but not limited to those resulting from * defects in Software and/or Documentation, or loss or inaccuracy of data of any * kind. * * @section Description * * See HWTopoLinux.cpp. * * @author Donald Nguyen <[email protected]> */ #include "Galois/Runtime/ll/HWTopo.h" #include "Galois/Runtime/ll/gio.h" #include <vector> #include <sched.h> using namespace Galois::Runtime::LL; namespace { static bool linuxBindToProcessor(int proc) { cpu_set_t mask; /* CPU_ZERO initializes all the bits in the mask to zero. */ CPU_ZERO( &mask ); /* CPU_SET sets only the bit corresponding to cpu. */ // void to cancel unused result warning (void)CPU_SET( proc, &mask ); /* sched_setaffinity returns 0 in success */ if( sched_setaffinity( 0, sizeof(mask), &mask ) == -1 ) { gWarn("Could not set CPU affinity for thread ", proc, "(", strerror(errno), ")"); return false; } return true; } //! Flat machine with the correct number of threads and binding struct Policy { std::vector<int> procmap; //Galois id -> cpu id unsigned numThreads, numCores, numPackages; Policy() { #if 1 for (int i = 0; i < 16; ++i) { for (int j = 0; j < 4; ++j) { procmap.push_back(j*16 + i); } } #else int cpuid_max = 63; for (int i = 0; i <= cpuid_max; i++) { procmap.push_back(i); } #endif numThreads = procmap.size(); numCores = procmap.size(); numPackages = 1; } }; Policy& getPolicy() { static Policy A; return A; } } //namespace bool Galois::Runtime::LL::bindThreadToProcessor(int id) { return linuxBindToProcessor(getPolicy().procmap[id]); } unsigned Galois::Runtime::LL::getProcessorForThread(int id) { return getPolicy().procmap[id]; } unsigned Galois::Runtime::LL::getMaxThreads() { return getPolicy().numThreads; } unsigned Galois::Runtime::LL::getMaxCores() { return getPolicy().numCores; } unsigned Galois::Runtime::LL::getMaxPackages() { return getPolicy().numPackages; } unsigned Galois::Runtime::LL::getMaxPackageForThread(int id) { return getPolicy().numPackages - 1; } unsigned Galois::Runtime::LL::getPackageForThread(int id) { return 0; } bool Galois::Runtime::LL::isPackageLeader(int id) { return id == 0; } unsigned Galois::Runtime::LL::getLeaderForThread(int id) { return 0; } unsigned Galois::Runtime::LL::getLeaderForPackage(int id) { return 0; }
0
rapidsai_public_repos/code-share/maxflow/galois/src
rapidsai_public_repos/code-share/maxflow/galois/src/mm/CMakeLists.txt
add_internal_library(mm Mem.cpp NumaMem.cpp PageAlloc.cpp)
0
rapidsai_public_repos/code-share/maxflow/galois/src
rapidsai_public_repos/code-share/maxflow/galois/src/mm/Mem.cpp
/** Memory allocator implementation -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @section Description * * Strongly inspired by heap layers: * http://www.heaplayers.org/ * FSB is modified from: * http://warp.povusers.org/FSBAllocator/ * * @author Andrew Lenharth <[email protected]> */ #include "Galois/Runtime/mm/Mem.h" //#include "Galois/Runtime/Support.h" #include <map> using namespace Galois::Runtime; using namespace MM; using namespace LL; //Anchor the class SystemBaseAlloc::SystemBaseAlloc() {} SystemBaseAlloc::~SystemBaseAlloc() {} PtrLock<SizedAllocatorFactory, true> SizedAllocatorFactory::instance; __thread SizedAllocatorFactory::AllocatorsMap* SizedAllocatorFactory::localAllocators = 0; #ifndef USEMALLOC SizedAllocatorFactory::SizedAlloc* SizedAllocatorFactory::getAllocatorForSize(const size_t size) { if (size == 0) return 0; return getInstance()->getAllocForSize(size); } SizedAllocatorFactory::SizedAlloc* SizedAllocatorFactory::getAllocForSize(const size_t size) { typedef SizedAllocatorFactory::AllocatorsMap AllocMap; if (!localAllocators) localAllocators = new AllocMap; auto& lentry = (*localAllocators)[size]; if (lentry) return lentry; lock.lock(); auto& gentry = allocators[size]; if (!gentry) gentry = new SizedAlloc(); lentry = gentry; lock.unlock(); return lentry; } SizedAllocatorFactory* SizedAllocatorFactory::getInstance() { SizedAllocatorFactory* f = instance.getValue(); if (f) return f; instance.lock(); f = instance.getValue(); if (f) { instance.unlock(); } else { f = new SizedAllocatorFactory(); instance.unlock_and_set(f); } return f; } SizedAllocatorFactory::SizedAllocatorFactory() :lock() {} SizedAllocatorFactory::~SizedAllocatorFactory() { for (AllocatorsMap::iterator it = allocators.begin(), end = allocators.end(); it != end; ++it) { delete it->second; } } #endif
0
rapidsai_public_repos/code-share/maxflow/galois/src
rapidsai_public_repos/code-share/maxflow/galois/src/mm/PageAlloc.cpp
/** Page Allocator Implementation -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @section Description * * @author Andrew Lenharth <[email protected]> */ #include "Galois/Runtime/mm/Mem.h" #include "Galois/Runtime/ll/gio.h" #include "Galois/Runtime/ll/StaticInstance.h" #include <sys/mman.h> #include <map> #include <vector> #include <numeric> // mmap flags static const int _PROT = PROT_READ | PROT_WRITE; static const int _MAP_BASE = MAP_ANONYMOUS | MAP_PRIVATE; #ifdef MAP_POPULATE static const int _MAP_POP = MAP_POPULATE | _MAP_BASE; #endif #ifdef MAP_HUGETLB static const int _MAP_HUGE_POP = MAP_HUGETLB | _MAP_POP; static const int _MAP_HUGE = MAP_HUGETLB; #endif namespace { struct FreeNode { FreeNode* next; }; typedef Galois::Runtime::LL::PtrLock<FreeNode, true> HeadPtr; typedef Galois::Runtime::LL::CacheLineStorage<HeadPtr> HeadPtrStorage; // Tracks pages allocated struct PAState { std::vector<int> counts; std::map<void*, HeadPtr*> ownerMap; PAState() { counts.resize(Galois::Runtime::LL::getMaxThreads(), 0); } }; static Galois::Runtime::LL::StaticInstance<PAState> PA; #ifdef __linux__ #define DoAllocLock true #else #define DoAllocLock false #endif static Galois::Runtime::LL::SimpleLock<DoAllocLock> allocLock; static Galois::Runtime::LL::SimpleLock<true> dataLock; static __thread HeadPtr* head = 0; void* allocFromOS() { //linux mmap can introduce unbounded sleep! allocLock.lock(); void* ptr = 0; #ifdef MAP_HUGETLB //First try huge ptr = mmap(0, Galois::Runtime::MM::pageSize, _PROT, _MAP_HUGE_POP, -1, 0); #endif //FIXME: improve failure case to ensure pageSize alignment #ifdef MAP_POPULATE //Then try populate if (!ptr || ptr == MAP_FAILED) ptr = mmap(0, Galois::Runtime::MM::pageSize, _PROT, _MAP_POP, -1, 0); #endif //Then try normal if (!ptr || ptr == MAP_FAILED) { ptr = mmap(0, Galois::Runtime::MM::pageSize, _PROT, _MAP_BASE, -1, 0); } allocLock.unlock(); if (!ptr || ptr == MAP_FAILED) { GALOIS_SYS_DIE("Out of Memory"); } //protect the tracking structures dataLock.lock(); HeadPtr*& h = head; if (!h) { //first allocation h = &((new HeadPtrStorage())->data); } PAState& p = *PA.get(); p.ownerMap[ptr] = h; p.counts[Galois::Runtime::LL::getTID()] += 1; dataLock.unlock(); return ptr; } } // end anon namespace void Galois::Runtime::MM::pageIn(void* buf, size_t len) { volatile char* ptr = reinterpret_cast<volatile char*>(buf); for (size_t i = 0; i < len; i += smallPageSize) ptr[i]; } void* Galois::Runtime::MM::pageAlloc() { HeadPtr* phead = head; if (phead) { phead->lock(); FreeNode* h = phead->getValue(); if (h) { phead->unlock_and_set(h->next); return h; } phead->unlock(); } return allocFromOS(); } void Galois::Runtime::MM::pageFree(void* m) { dataLock.lock(); HeadPtr* phead = PA.get()->ownerMap[m]; dataLock.unlock(); assert(phead); phead->lock(); FreeNode* nh = reinterpret_cast<FreeNode*>(m); nh->next = phead->getValue(); phead->unlock_and_set(nh); } void Galois::Runtime::MM::pagePreAlloc(int numPages) { while (numPages--) Galois::Runtime::MM::pageFree(allocFromOS()); } int Galois::Runtime::MM::numPageAllocTotal() { PAState& p = *PA.get(); return std::accumulate(p.counts.begin(), p.counts.end(), 0); } int Galois::Runtime::MM::numPageAllocForThread(unsigned tid) { return PA.get()->counts[tid]; } void* Galois::Runtime::MM::largeAlloc(size_t len, bool preFault) { size_t size = (len + pageSize - 1) & (~(size_t)(pageSize - 1)); void * ptr = 0; allocLock.lock(); #ifdef MAP_HUGETLB ptr = mmap(0, size, _PROT, preFault ? _MAP_HUGE_POP : _MAP_HUGE, -1, 0); # ifndef MAP_POPULATE if (ptr != MAP_FAILED && ptr && preFault) { pageIn(ptr, size); // XXX should use hugepage stride } # endif #endif #ifdef MAP_POPULATE if (preFault && (!ptr || ptr == MAP_FAILED)) ptr = mmap(0, size, _PROT, _MAP_POP, -1, 0); #endif if (!ptr || ptr == MAP_FAILED) { ptr = mmap(0, size, _PROT, _MAP_BASE, -1, 0); if (ptr != MAP_FAILED && ptr && preFault) { pageIn(ptr, size); } } allocLock.unlock(); if (!ptr || ptr == MAP_FAILED) GALOIS_SYS_DIE("Out of Memory"); return ptr; } void Galois::Runtime::MM::largeFree(void* m, size_t len) { size_t size = (len + pageSize - 1) & (~(size_t)(pageSize - 1)); allocLock.lock(); munmap(m, size); allocLock.unlock(); }
0
rapidsai_public_repos/code-share/maxflow/galois/src
rapidsai_public_repos/code-share/maxflow/galois/src/mm/NumaMem.cpp
/** Memory allocator implementation -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2013, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @section Description * * @author Andrew Lenharth <[email protected]> */ #include "Galois/config.h" #include "Galois/Runtime/mm/Mem.h" #include "Galois/Runtime/ll/gio.h" #if defined(GALOIS_USE_NUMA) && !defined(GALOIS_FORCE_NO_NUMA) #define USE_NUMA #endif #ifdef USE_NUMA #include <numa.h> #endif #ifdef USE_NUMA static int is_numa_available; #endif // TODO Remove dependency on USE_NUMA for non-interleaved functionality because // libnuma dev is not widely available static const char* sNumaStat = "/proc/self/numa_maps"; void Galois::Runtime::MM::printInterleavedStats(int minPages) { FILE* f = fopen(sNumaStat, "r"); if (!f) { LL::gInfo("No NUMA support"); return; //GALOIS_SYS_DIE("failed opening ", sNumaStat); } char line[2048]; LL::gInfo("INTERLEAVED STATS BEGIN"); while (fgets(line, sizeof(line)/sizeof(*line), f)) { // Chomp \n size_t len = strlen(line); if (len && line[len-1] == '\n') line[len-1] = '\0'; char* start; if (strstr(line, "interleave") != 0) { LL::gInfo(line); } else if ((start = strstr(line, "anon=")) != 0) { int pages; if (sscanf(start, "anon=%d", &pages) == 1 && pages >= minPages) { LL::gInfo(line); } } else if ((start = strstr(line, "mapped=")) != 0) { int pages; if (sscanf(start, "mapped=%d", &pages) == 1 && pages >= minPages) { LL::gInfo(line); } } } LL::gInfo("INTERLEAVED STATS END"); fclose(f); } static int num_numa_pages_for(unsigned nodeid) { FILE* f = fopen(sNumaStat, "r"); if (!f) { //Galois::Runtime::LL::gInfo("No NUMA support"); return 0; } char format[2048]; char search[2048]; int written; written = snprintf(format, sizeof(format)/sizeof(*format), "N%u=%%d", nodeid); assert((unsigned)written < sizeof(format)/sizeof(*format)); written = snprintf(search, sizeof(search)/sizeof(*search), "N%u=", nodeid); assert((unsigned)written < sizeof(search)/sizeof(*search)); char line[2048]; int totalPages = 0; while (fgets(line, sizeof(line)/sizeof(*line), f)) { char* start; if ((start = strstr(line, search)) != 0) { int pages; if (sscanf(start, format, &pages) == 1) { totalPages += pages; } } } fclose(f); return totalPages; } static int check_numa() { #ifdef USE_NUMA if (is_numa_available == 0) { is_numa_available = numa_available() == -1 ? -1 : 1; if (is_numa_available == -1) Galois::Runtime::LL::gWarn("NUMA not available"); } return is_numa_available == 1; #else return false; #endif } int Galois::Runtime::MM::numNumaAllocForNode(unsigned nodeid) { return num_numa_pages_for(nodeid); } int Galois::Runtime::MM::numNumaNodes() { if (!check_numa()) return 1; #ifdef USE_NUMA return numa_num_configured_nodes(); #else return 1; #endif } #ifdef USE_NUMA static void *alloc_interleaved_subset(size_t len) { void* data = 0; # if defined(GALOIS_USE_NUMA_OLD) && !defined(GALOIS_FORCE_NO_NUMA) nodemask_t nm = numa_no_nodes; unsigned int num = Galois::Runtime::activeThreads; int num_nodes = numa_num_configured_nodes(); for (unsigned y = 0; y < num; ++y) { unsigned proc = Galois::Runtime::LL::getProcessorForThread(y); // Assume block distribution from physical processors to numa nodes nodemask_set(&nm, proc/num_nodes); } data = numa_alloc_interleaved_subset(len, &nm); # elif defined(GALOIS_USE_NUMA) && !defined(GALOIS_FORCE_NO_NUMA) bitmask* nm = numa_allocate_nodemask(); unsigned int num = Galois::Runtime::activeThreads; for (unsigned y = 0; y < num; ++y) { unsigned proc = Galois::Runtime::LL::getProcessorForThread(y); int node = numa_node_of_cpu(proc); numa_bitmask_setbit(nm, node); } data = numa_alloc_interleaved_subset(len, nm); numa_free_nodemask(nm); # else data = Galois::Runtime::MM::largeAlloc(len); # endif return data; } #endif void* Galois::Runtime::MM::largeInterleavedAlloc(size_t len, bool full) { void* data = 0; #ifdef USE_NUMA if (check_numa()) { if (full) data = numa_alloc_interleaved(len); else data = alloc_interleaved_subset(len); // NB(ddn): Some strange bugs when empty interleaved mappings are // coalesced. Eagerly fault in interleaved pages to circumvent. pageIn(data, len); } else { data = largeAlloc(len); } #else data = largeAlloc(len); #endif if (!data) abort(); return data; } void Galois::Runtime::MM::largeInterleavedFree(void* m, size_t len) { if (!check_numa()) largeFree(m, len); #ifdef USE_NUMA numa_free(m, len); #else largeFree(m, len); #endif }
0
rapidsai_public_repos/code-share/maxflow/galois/src
rapidsai_public_repos/code-share/maxflow/galois/src/llvm/SmallPtrSet.cpp
//===- llvm/ADT/SmallPtrSet.cpp - 'Normally small' pointer set ------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the SmallPtrSet class. See SmallPtrSet.h for an // overview of the algorithm. // //===----------------------------------------------------------------------===// #include "llvm/ADT/SmallPtrSet.h" #include "llvm/Support/MathExtras.h" #include <cstdlib> using namespace llvm; void SmallPtrSetImpl::shrink_and_clear() { assert(!isSmall() && "Can't shrink a small set!"); free(CurArray); // Reduce the number of buckets. CurArraySize = NumElements > 16 ? 1 << (Log2_32_Ceil(NumElements) + 1) : 32; NumElements = NumTombstones = 0; // Install the new array. Clear all the buckets to empty. CurArray = (const void**)malloc(sizeof(void*) * (CurArraySize+1)); assert(CurArray && "Failed to allocate memory?"); memset(CurArray, -1, CurArraySize*sizeof(void*)); // The end pointer, always valid, is set to a valid element to help the // iterator. CurArray[CurArraySize] = 0; } bool SmallPtrSetImpl::insert_imp(const void * Ptr) { if (isSmall()) { // Check to see if it is already in the set. for (const void **APtr = SmallArray, **E = SmallArray+NumElements; APtr != E; ++APtr) if (*APtr == Ptr) return false; // Nope, there isn't. If we stay small, just 'pushback' now. if (NumElements < CurArraySize-1) { SmallArray[NumElements++] = Ptr; return true; } // Otherwise, hit the big set case, which will call grow. } if (NumElements*4 >= CurArraySize*3) { // If more than 3/4 of the array is full, grow. Grow(CurArraySize < 64 ? 128 : CurArraySize*2); } else if (CurArraySize-(NumElements+NumTombstones) < CurArraySize/8) { // If fewer of 1/8 of the array is empty (meaning that many are filled with // tombstones), rehash. Grow(CurArraySize); } // Okay, we know we have space. Find a hash bucket. const void **Bucket = const_cast<const void**>(FindBucketFor(Ptr)); if (*Bucket == Ptr) return false; // Already inserted, good. // Otherwise, insert it! if (*Bucket == getTombstoneMarker()) --NumTombstones; *Bucket = Ptr; ++NumElements; // Track density. return true; } bool SmallPtrSetImpl::erase_imp(const void * Ptr) { if (isSmall()) { // Check to see if it is in the set. for (const void **APtr = SmallArray, **E = SmallArray+NumElements; APtr != E; ++APtr) if (*APtr == Ptr) { // If it is in the set, replace this element. *APtr = E[-1]; E[-1] = getEmptyMarker(); --NumElements; return true; } return false; } // Okay, we know we have space. Find a hash bucket. void **Bucket = const_cast<void**>(FindBucketFor(Ptr)); if (*Bucket != Ptr) return false; // Not in the set? // Set this as a tombstone. *Bucket = getTombstoneMarker(); --NumElements; ++NumTombstones; return true; } const void * const *SmallPtrSetImpl::FindBucketFor(const void *Ptr) const { unsigned Bucket = Hash(Ptr); unsigned ArraySize = CurArraySize; unsigned ProbeAmt = 1; const void *const *Array = CurArray; const void *const *Tombstone = 0; while (1) { // Found Ptr's bucket? if (Array[Bucket] == Ptr) return Array+Bucket; // If we found an empty bucket, the pointer doesn't exist in the set. // Return a tombstone if we've seen one so far, or the empty bucket if // not. if (Array[Bucket] == getEmptyMarker()) return Tombstone ? Tombstone : Array+Bucket; // If this is a tombstone, remember it. If Ptr ends up not in the set, we // prefer to return it than something that would require more probing. if (Array[Bucket] == getTombstoneMarker() && !Tombstone) Tombstone = Array+Bucket; // Remember the first tombstone found. // It's a hash collision or a tombstone. Reprobe. Bucket = (Bucket + ProbeAmt++) & (ArraySize-1); } } /// Grow - Allocate a larger backing store for the buckets and move it over. /// void SmallPtrSetImpl::Grow(unsigned NewSize) { // Allocate at twice as many buckets, but at least 128. unsigned OldSize = CurArraySize; const void **OldBuckets = CurArray; bool WasSmall = isSmall(); // Install the new array. Clear all the buckets to empty. CurArray = (const void**)malloc(sizeof(void*) * (NewSize+1)); assert(CurArray && "Failed to allocate memory?"); CurArraySize = NewSize; memset(CurArray, -1, NewSize*sizeof(void*)); // The end pointer, always valid, is set to a valid element to help the // iterator. CurArray[NewSize] = 0; // Copy over all the elements. if (WasSmall) { // Small sets store their elements in order. for (const void **BucketPtr = OldBuckets, **E = OldBuckets+NumElements; BucketPtr != E; ++BucketPtr) { const void *Elt = *BucketPtr; *const_cast<void**>(FindBucketFor(Elt)) = const_cast<void*>(Elt); } } else { // Copy over all valid entries. for (const void **BucketPtr = OldBuckets, **E = OldBuckets+OldSize; BucketPtr != E; ++BucketPtr) { // Copy over the element if it is valid. const void *Elt = *BucketPtr; if (Elt != getTombstoneMarker() && Elt != getEmptyMarker()) *const_cast<void**>(FindBucketFor(Elt)) = const_cast<void*>(Elt); } free(OldBuckets); NumTombstones = 0; } } SmallPtrSetImpl::SmallPtrSetImpl(const void **SmallStorage, const SmallPtrSetImpl& that) { SmallArray = SmallStorage; // If we're becoming small, prepare to insert into our stack space if (that.isSmall()) { CurArray = SmallArray; // Otherwise, allocate new heap space (unless we were the same size) } else { CurArray = (const void**)malloc(sizeof(void*) * (that.CurArraySize+1)); assert(CurArray && "Failed to allocate memory?"); } // Copy over the new array size CurArraySize = that.CurArraySize; // Copy over the contents from the other set memcpy(CurArray, that.CurArray, sizeof(void*)*(CurArraySize+1)); NumElements = that.NumElements; NumTombstones = that.NumTombstones; } /// CopyFrom - implement operator= from a smallptrset that has the same pointer /// type, but may have a different small size. void SmallPtrSetImpl::CopyFrom(const SmallPtrSetImpl &RHS) { if (isSmall() && RHS.isSmall()) assert(CurArraySize == RHS.CurArraySize && "Cannot assign sets with different small sizes"); // If we're becoming small, prepare to insert into our stack space if (RHS.isSmall()) { if (!isSmall()) free(CurArray); CurArray = SmallArray; // Otherwise, allocate new heap space (unless we were the same size) } else if (CurArraySize != RHS.CurArraySize) { if (isSmall()) CurArray = (const void**)malloc(sizeof(void*) * (RHS.CurArraySize+1)); else CurArray = (const void**)realloc(CurArray, sizeof(void*)*(RHS.CurArraySize+1)); assert(CurArray && "Failed to allocate memory?"); } // Copy over the new array size CurArraySize = RHS.CurArraySize; // Copy over the contents from the other set memcpy(CurArray, RHS.CurArray, sizeof(void*)*(CurArraySize+1)); NumElements = RHS.NumElements; NumTombstones = RHS.NumTombstones; } SmallPtrSetImpl::~SmallPtrSetImpl() { if (!isSmall()) free(CurArray); }
0
rapidsai_public_repos/code-share/maxflow/galois/src
rapidsai_public_repos/code-share/maxflow/galois/src/llvm/StringRef.cpp
//===-- StringRef.cpp - Lightweight String References ---------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/StringRef.h" #include "llvm/ADT/APInt.h" #include "llvm/ADT/OwningPtr.h" #include <bitset> using namespace llvm; // MSVC emits references to this into the translation units which reference it. #ifndef _MSC_VER const size_t StringRef::npos; #endif static char ascii_tolower(char x) { if (x >= 'A' && x <= 'Z') return x - 'A' + 'a'; return x; } static bool ascii_isdigit(char x) { return x >= '0' && x <= '9'; } /// compare_lower - Compare strings, ignoring case. int StringRef::compare_lower(StringRef RHS) const { for (size_t I = 0, E = min(Length, RHS.Length); I != E; ++I) { unsigned char LHC = ascii_tolower(Data[I]); unsigned char RHC = ascii_tolower(RHS.Data[I]); if (LHC != RHC) return LHC < RHC ? -1 : 1; } if (Length == RHS.Length) return 0; return Length < RHS.Length ? -1 : 1; } /// compare_numeric - Compare strings, handle embedded numbers. int StringRef::compare_numeric(StringRef RHS) const { for (size_t I = 0, E = min(Length, RHS.Length); I != E; ++I) { // Check for sequences of digits. if (ascii_isdigit(Data[I]) && ascii_isdigit(RHS.Data[I])) { // The longer sequence of numbers is considered larger. // This doesn't really handle prefixed zeros well. size_t J; for (J = I + 1; J != E + 1; ++J) { bool ld = J < Length && ascii_isdigit(Data[J]); bool rd = J < RHS.Length && ascii_isdigit(RHS.Data[J]); if (ld != rd) return rd ? -1 : 1; if (!rd) break; } // The two number sequences have the same length (J-I), just memcmp them. if (int Res = compareMemory(Data + I, RHS.Data + I, J - I)) return Res < 0 ? -1 : 1; // Identical number sequences, continue search after the numbers. I = J - 1; continue; } if (Data[I] != RHS.Data[I]) return (unsigned char)Data[I] < (unsigned char)RHS.Data[I] ? -1 : 1; } if (Length == RHS.Length) return 0; return Length < RHS.Length ? -1 : 1; } // Compute the edit distance between the two given strings. unsigned StringRef::edit_distance(llvm::StringRef Other, bool AllowReplacements, unsigned MaxEditDistance) { // The algorithm implemented below is the "classic" // dynamic-programming algorithm for computing the Levenshtein // distance, which is described here: // // http://en.wikipedia.org/wiki/Levenshtein_distance // // Although the algorithm is typically described using an m x n // array, only two rows are used at a time, so this implemenation // just keeps two separate vectors for those two rows. size_type m = size(); size_type n = Other.size(); const unsigned SmallBufferSize = 64; unsigned SmallBuffer[SmallBufferSize]; llvm::OwningArrayPtr<unsigned> Allocated; unsigned *previous = SmallBuffer; if (2*(n + 1) > SmallBufferSize) { previous = new unsigned [2*(n+1)]; Allocated.reset(previous); } unsigned *current = previous + (n + 1); for (unsigned i = 0; i <= n; ++i) previous[i] = i; for (size_type y = 1; y <= m; ++y) { current[0] = y; unsigned BestThisRow = current[0]; for (size_type x = 1; x <= n; ++x) { if (AllowReplacements) { current[x] = min(previous[x-1] + ((*this)[y-1] == Other[x-1]? 0u:1u), min(current[x-1], previous[x])+1); } else { if ((*this)[y-1] == Other[x-1]) current[x] = previous[x-1]; else current[x] = min(current[x-1], previous[x]) + 1; } BestThisRow = min(BestThisRow, current[x]); } if (MaxEditDistance && BestThisRow > MaxEditDistance) return MaxEditDistance + 1; unsigned *tmp = current; current = previous; previous = tmp; } unsigned Result = previous[n]; return Result; } //===----------------------------------------------------------------------===// // String Searching //===----------------------------------------------------------------------===// /// find - Search for the first string \arg Str in the string. /// /// \return - The index of the first occurrence of \arg Str, or npos if not /// found. size_t StringRef::find(StringRef Str, size_t From) const { size_t N = Str.size(); if (N > Length) return npos; for (size_t e = Length - N + 1, i = min(From, e); i != e; ++i) if (substr(i, N).equals(Str)) return i; return npos; } /// rfind - Search for the last string \arg Str in the string. /// /// \return - The index of the last occurrence of \arg Str, or npos if not /// found. size_t StringRef::rfind(StringRef Str) const { size_t N = Str.size(); if (N > Length) return npos; for (size_t i = Length - N + 1, e = 0; i != e;) { --i; if (substr(i, N).equals(Str)) return i; } return npos; } /// find_first_of - Find the first character in the string that is in \arg /// Chars, or npos if not found. /// /// Note: O(size() + Chars.size()) StringRef::size_type StringRef::find_first_of(StringRef Chars, size_t From) const { std::bitset<1 << CHAR_BIT> CharBits; for (size_type i = 0; i != Chars.size(); ++i) CharBits.set((unsigned char)Chars[i]); for (size_type i = min(From, Length), e = Length; i != e; ++i) if (CharBits.test((unsigned char)Data[i])) return i; return npos; } /// find_first_not_of - Find the first character in the string that is not /// \arg C or npos if not found. StringRef::size_type StringRef::find_first_not_of(char C, size_t From) const { for (size_type i = min(From, Length), e = Length; i != e; ++i) if (Data[i] != C) return i; return npos; } /// find_first_not_of - Find the first character in the string that is not /// in the string \arg Chars, or npos if not found. /// /// Note: O(size() + Chars.size()) StringRef::size_type StringRef::find_first_not_of(StringRef Chars, size_t From) const { std::bitset<1 << CHAR_BIT> CharBits; for (size_type i = 0; i != Chars.size(); ++i) CharBits.set((unsigned char)Chars[i]); for (size_type i = min(From, Length), e = Length; i != e; ++i) if (!CharBits.test((unsigned char)Data[i])) return i; return npos; } /// find_last_of - Find the last character in the string that is in \arg C, /// or npos if not found. /// /// Note: O(size() + Chars.size()) StringRef::size_type StringRef::find_last_of(StringRef Chars, size_t From) const { std::bitset<1 << CHAR_BIT> CharBits; for (size_type i = 0; i != Chars.size(); ++i) CharBits.set((unsigned char)Chars[i]); for (size_type i = min(From, Length) - 1, e = -1; i != e; --i) if (CharBits.test((unsigned char)Data[i])) return i; return npos; } //===----------------------------------------------------------------------===// // Helpful Algorithms //===----------------------------------------------------------------------===// /// count - Return the number of non-overlapped occurrences of \arg Str in /// the string. size_t StringRef::count(StringRef Str) const { size_t Count = 0; size_t N = Str.size(); if (N > Length) return 0; for (size_t i = 0, e = Length - N + 1; i != e; ++i) if (substr(i, N).equals(Str)) ++Count; return Count; } static unsigned GetAutoSenseRadix(StringRef &Str) { if (Str.startswith("0x")) { Str = Str.substr(2); return 16; } else if (Str.startswith("0b")) { Str = Str.substr(2); return 2; } else if (Str.startswith("0")) { return 8; } else { return 10; } } /// GetAsUnsignedInteger - Workhorse method that converts a integer character /// sequence of radix up to 36 to an unsigned long long value. static bool GetAsUnsignedInteger(StringRef Str, unsigned Radix, unsigned long long &Result) { // Autosense radix if not specified. if (Radix == 0) Radix = GetAutoSenseRadix(Str); // Empty strings (after the radix autosense) are invalid. if (Str.empty()) return true; // Parse all the bytes of the string given this radix. Watch for overflow. Result = 0; while (!Str.empty()) { unsigned CharVal; if (Str[0] >= '0' && Str[0] <= '9') CharVal = Str[0]-'0'; else if (Str[0] >= 'a' && Str[0] <= 'z') CharVal = Str[0]-'a'+10; else if (Str[0] >= 'A' && Str[0] <= 'Z') CharVal = Str[0]-'A'+10; else return true; // If the parsed value is larger than the integer radix, the string is // invalid. if (CharVal >= Radix) return true; // Add in this character. unsigned long long PrevResult = Result; Result = Result*Radix+CharVal; // Check for overflow. if (Result < PrevResult) return true; Str = Str.substr(1); } return false; } bool StringRef::getAsInteger(unsigned Radix, unsigned long long &Result) const { return GetAsUnsignedInteger(*this, Radix, Result); } bool StringRef::getAsInteger(unsigned Radix, long long &Result) const { unsigned long long ULLVal; // Handle positive strings first. if (empty() || front() != '-') { if (GetAsUnsignedInteger(*this, Radix, ULLVal) || // Check for value so large it overflows a signed value. (long long)ULLVal < 0) return true; Result = ULLVal; return false; } // Get the positive part of the value. if (GetAsUnsignedInteger(substr(1), Radix, ULLVal) || // Reject values so large they'd overflow as negative signed, but allow // "-0". This negates the unsigned so that the negative isn't undefined // on signed overflow. (long long)-ULLVal > 0) return true; Result = -ULLVal; return false; } bool StringRef::getAsInteger(unsigned Radix, int &Result) const { long long Val; if (getAsInteger(Radix, Val) || (int)Val != Val) return true; Result = Val; return false; } bool StringRef::getAsInteger(unsigned Radix, unsigned &Result) const { unsigned long long Val; if (getAsInteger(Radix, Val) || (unsigned)Val != Val) return true; Result = Val; return false; } bool StringRef::getAsInteger(unsigned Radix, APInt &Result) const { StringRef Str = *this; // Autosense radix if not specified. if (Radix == 0) Radix = GetAutoSenseRadix(Str); assert(Radix > 1 && Radix <= 36); // Empty strings (after the radix autosense) are invalid. if (Str.empty()) return true; // Skip leading zeroes. This can be a significant improvement if // it means we don't need > 64 bits. while (!Str.empty() && Str.front() == '0') Str = Str.substr(1); // If it was nothing but zeroes.... if (Str.empty()) { Result = APInt(64, 0); return false; } // (Over-)estimate the required number of bits. unsigned Log2Radix = 0; while ((1U << Log2Radix) < Radix) Log2Radix++; bool IsPowerOf2Radix = ((1U << Log2Radix) == Radix); unsigned BitWidth = Log2Radix * Str.size(); if (BitWidth < Result.getBitWidth()) BitWidth = Result.getBitWidth(); // don't shrink the result else Result = Result.zext(BitWidth); APInt RadixAP, CharAP; // unused unless !IsPowerOf2Radix if (!IsPowerOf2Radix) { // These must have the same bit-width as Result. RadixAP = APInt(BitWidth, Radix); CharAP = APInt(BitWidth, 0); } // Parse all the bytes of the string given this radix. Result = 0; while (!Str.empty()) { unsigned CharVal; if (Str[0] >= '0' && Str[0] <= '9') CharVal = Str[0]-'0'; else if (Str[0] >= 'a' && Str[0] <= 'z') CharVal = Str[0]-'a'+10; else if (Str[0] >= 'A' && Str[0] <= 'Z') CharVal = Str[0]-'A'+10; else return true; // If the parsed value is larger than the integer radix, the string is // invalid. if (CharVal >= Radix) return true; // Add in this character. if (IsPowerOf2Radix) { Result <<= Log2Radix; Result |= CharVal; } else { Result *= RadixAP; CharAP = CharVal; Result += CharAP; } Str = Str.substr(1); } return false; }
0
rapidsai_public_repos/code-share/maxflow/galois/src
rapidsai_public_repos/code-share/maxflow/galois/src/llvm/CMakeLists.txt
add_internal_library(llvm Allocator.cpp APFloat.cpp APInt.cpp CommandLine.cpp SmallPtrSet.cpp SmallVector.cpp StringMap.cpp StringRef.cpp Twine.cpp) #HACK(ddn): Workaround for bug in Clang-BGQ compiler: #clang version 3.4 #([email protected]:src/llvm-trunk/tools/clang c210ac88e0d229a47343d2162f29f87827f515d1) #([email protected]:src/llvm-trunk 29d31684b696d035f6352c36511267689a0501dd) if(CMAKE_SYSTEM_NAME MATCHES "BlueGeneQ" AND CMAKE_CXX_COMPILER_ID MATCHES "Clang") set_source_files_properties(CommandLine.cpp PROPERTIES COMPILE_FLAGS "-O0") endif()
0
rapidsai_public_repos/code-share/maxflow/galois/src
rapidsai_public_repos/code-share/maxflow/galois/src/llvm/Allocator.cpp
//===--- Allocator.cpp - Simple memory allocation abstraction -------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the BumpPtrAllocator interface. // //===----------------------------------------------------------------------===// #include "llvm/Support/Allocator.h" #include "llvm/Support/DataTypes.h" #include "llvm/Support/Recycler.h" #include "llvm/Support/Memory.h" #include <cstring> #include <iostream> namespace llvm { BumpPtrAllocator::BumpPtrAllocator(size_t size, size_t threshold, SlabAllocator &allocator) : SlabSize(size), SizeThreshold(threshold), Allocator(allocator), CurSlab(0), BytesAllocated(0) { } BumpPtrAllocator::~BumpPtrAllocator() { DeallocateSlabs(CurSlab); } /// AlignPtr - Align Ptr to Alignment bytes, rounding up. Alignment should /// be a power of two. This method rounds up, so AlignPtr(7, 4) == 8 and /// AlignPtr(8, 4) == 8. char *BumpPtrAllocator::AlignPtr(char *Ptr, size_t Alignment) { assert(Alignment && (Alignment & (Alignment - 1)) == 0 && "Alignment is not a power of two!"); // Do the alignment. return (char*)(((uintptr_t)Ptr + Alignment - 1) & ~(uintptr_t)(Alignment - 1)); } /// StartNewSlab - Allocate a new slab and move the bump pointers over into /// the new slab. Modifies CurPtr and End. void BumpPtrAllocator::StartNewSlab() { // If we allocated a big number of slabs already it's likely that we're going // to allocate more. Increase slab size to reduce mallocs and possibly memory // overhead. The factors are chosen conservatively to avoid overallocation. if (BytesAllocated >= SlabSize * 128) SlabSize *= 2; MemSlab *NewSlab = Allocator.Allocate(SlabSize); NewSlab->NextPtr = CurSlab; CurSlab = NewSlab; CurPtr = (char*)(CurSlab + 1); End = ((char*)CurSlab) + CurSlab->Size; } /// DeallocateSlabs - Deallocate all memory slabs after and including this /// one. void BumpPtrAllocator::DeallocateSlabs(MemSlab *Slab) { while (Slab) { MemSlab *NextSlab = Slab->NextPtr; #ifndef NDEBUG // Poison the memory so stale pointers crash sooner. Note we must // preserve the Size and NextPtr fields at the beginning. sys::Memory::setRangeWritable(Slab + 1, Slab->Size - sizeof(MemSlab)); memset(Slab + 1, 0xCD, Slab->Size - sizeof(MemSlab)); #endif Allocator.Deallocate(Slab); Slab = NextSlab; } } /// Reset - Deallocate all but the current slab and reset the current pointer /// to the beginning of it, freeing all memory allocated so far. void BumpPtrAllocator::Reset() { if (!CurSlab) return; DeallocateSlabs(CurSlab->NextPtr); CurSlab->NextPtr = 0; CurPtr = (char*)(CurSlab + 1); End = ((char*)CurSlab) + CurSlab->Size; } /// Allocate - Allocate space at the specified alignment. /// void *BumpPtrAllocator::Allocate(size_t Size, size_t Alignment) { if (!CurSlab) // Start a new slab if we haven't allocated one already. StartNewSlab(); // Keep track of how many bytes we've allocated. BytesAllocated += Size; // 0-byte alignment means 1-byte alignment. if (Alignment == 0) Alignment = 1; // Allocate the aligned space, going forwards from CurPtr. char *Ptr = AlignPtr(CurPtr, Alignment); // Check if we can hold it. if (Ptr + Size <= End) { CurPtr = Ptr + Size; return Ptr; } // If Size is really big, allocate a separate slab for it. size_t PaddedSize = Size + sizeof(MemSlab) + Alignment - 1; if (PaddedSize > SizeThreshold) { MemSlab *NewSlab = Allocator.Allocate(PaddedSize); // Put the new slab after the current slab, since we are not allocating // into it. NewSlab->NextPtr = CurSlab->NextPtr; CurSlab->NextPtr = NewSlab; Ptr = AlignPtr((char*)(NewSlab + 1), Alignment); assert((uintptr_t)Ptr + Size <= (uintptr_t)NewSlab + NewSlab->Size); return Ptr; } // Otherwise, start a new slab and try again. StartNewSlab(); Ptr = AlignPtr(CurPtr, Alignment); CurPtr = Ptr + Size; assert(CurPtr <= End && "Unable to allocate memory!"); return Ptr; } unsigned BumpPtrAllocator::GetNumSlabs() const { unsigned NumSlabs = 0; for (MemSlab *Slab = CurSlab; Slab != 0; Slab = Slab->NextPtr) { ++NumSlabs; } return NumSlabs; } size_t BumpPtrAllocator::getTotalMemory() const { size_t TotalMemory = 0; for (MemSlab *Slab = CurSlab; Slab != 0; Slab = Slab->NextPtr) { TotalMemory += Slab->Size; } return TotalMemory; } void BumpPtrAllocator::PrintStats() const { unsigned NumSlabs = 0; size_t TotalMemory = 0; for (MemSlab *Slab = CurSlab; Slab != 0; Slab = Slab->NextPtr) { TotalMemory += Slab->Size; ++NumSlabs; } std::cerr << "\nNumber of memory regions: " << NumSlabs << '\n' << "Bytes used: " << BytesAllocated << '\n' << "Bytes allocated: " << TotalMemory << '\n' << "Bytes wasted: " << (TotalMemory - BytesAllocated) << " (includes alignment, etc)\n"; } MallocSlabAllocator BumpPtrAllocator::DefaultSlabAllocator = MallocSlabAllocator(); SlabAllocator::~SlabAllocator() { } MallocSlabAllocator::~MallocSlabAllocator() { } MemSlab *MallocSlabAllocator::Allocate(size_t Size) { MemSlab *Slab = (MemSlab*)Allocator.Allocate(Size, 0); Slab->Size = Size; Slab->NextPtr = 0; return Slab; } void MallocSlabAllocator::Deallocate(MemSlab *Slab) { Allocator.Deallocate(Slab); } void PrintRecyclerStats(size_t Size, size_t Align, size_t FreeListSize) { std::cerr << "Recycler element size: " << Size << '\n' << "Recycler element alignment: " << Align << '\n' << "Number of elements free for recycling: " << FreeListSize << '\n'; } }
0
rapidsai_public_repos/code-share/maxflow/galois/src
rapidsai_public_repos/code-share/maxflow/galois/src/llvm/Twine.cpp
//===-- Twine.cpp - Fast Temporary String Concatenation -------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/Twine.h" #include "llvm/ADT/SmallString.h" #include <sstream> using namespace llvm; std::string Twine::str() const { // If we're storing only a std::string, just return it. if (LHSKind == StdStringKind && RHSKind == EmptyKind) return *LHS.stdString; // Otherwise, flatten and copy the contents first. SmallString<256> Vec; return toStringRef(Vec).str(); } void Twine::toVector(SmallVectorImpl<char> &Out) const { // raw_svector_ostream OS(Out); // print(OS); } StringRef Twine::toStringRef(SmallVectorImpl<char> &Out) const { if (isSingleStringRef()) return getSingleStringRef(); toVector(Out); return StringRef(Out.data(), Out.size()); } StringRef Twine::toNullTerminatedStringRef(SmallVectorImpl<char> &Out) const { if (isUnary()) { switch (getLHSKind()) { case CStringKind: // Already null terminated, yay! return StringRef(LHS.cString); case StdStringKind: { const std::string *str = LHS.stdString; return StringRef(str->c_str(), str->size()); } default: break; } } toVector(Out); Out.push_back(0); Out.pop_back(); return StringRef(Out.data(), Out.size()); } void Twine::printOneChild(std::ostream &OS, Child Ptr, NodeKind Kind) const { switch (Kind) { case Twine::NullKind: break; case Twine::EmptyKind: break; case Twine::TwineKind: Ptr.twine->print(OS); break; case Twine::CStringKind: OS << Ptr.cString; break; case Twine::StdStringKind: OS << *Ptr.stdString; break; case Twine::StringRefKind: OS << *Ptr.stringRef; break; case Twine::CharKind: OS << Ptr.character; break; case Twine::DecUIKind: OS << Ptr.decUI; break; case Twine::DecIKind: OS << Ptr.decI; break; case Twine::DecULKind: OS << *Ptr.decUL; break; case Twine::DecLKind: OS << *Ptr.decL; break; case Twine::DecULLKind: OS << *Ptr.decULL; break; case Twine::DecLLKind: OS << *Ptr.decLL; break; case Twine::UHexKind: OS << std::hex << *Ptr.uHex << std::dec; break; } } void Twine::printOneChildRepr(std::ostream &OS, Child Ptr, NodeKind Kind) const { switch (Kind) { case Twine::NullKind: OS << "null"; break; case Twine::EmptyKind: OS << "empty"; break; case Twine::TwineKind: OS << "rope:"; Ptr.twine->printRepr(OS); break; case Twine::CStringKind: OS << "cstring:\"" << Ptr.cString << "\""; break; case Twine::StdStringKind: OS << "std::string:\"" << Ptr.stdString << "\""; break; case Twine::StringRefKind: OS << "stringref:\"" << Ptr.stringRef << "\""; break; case Twine::CharKind: OS << "char:\"" << Ptr.character << "\""; break; case Twine::DecUIKind: OS << "decUI:\"" << Ptr.decUI << "\""; break; case Twine::DecIKind: OS << "decI:\"" << Ptr.decI << "\""; break; case Twine::DecULKind: OS << "decUL:\"" << *Ptr.decUL << "\""; break; case Twine::DecLKind: OS << "decL:\"" << *Ptr.decL << "\""; break; case Twine::DecULLKind: OS << "decULL:\"" << *Ptr.decULL << "\""; break; case Twine::DecLLKind: OS << "decLL:\"" << *Ptr.decLL << "\""; break; case Twine::UHexKind: OS << "uhex:\"" << Ptr.uHex << "\""; break; } } void Twine::print(std::ostream &OS) const { printOneChild(OS, LHS, getLHSKind()); printOneChild(OS, RHS, getRHSKind()); } void Twine::printRepr(std::ostream &OS) const { OS << "(Twine "; printOneChildRepr(OS, LHS, getLHSKind()); OS << " "; printOneChildRepr(OS, RHS, getRHSKind()); OS << ")"; } void Twine::dump() const { print(std::cerr); } void Twine::dumpRepr() const { printRepr(std::cerr); }
0
rapidsai_public_repos/code-share/maxflow/galois/src
rapidsai_public_repos/code-share/maxflow/galois/src/llvm/APFloat.cpp
//===-- APFloat.cpp - Implement APFloat class -----------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements a class to represent arbitrary precision floating // point values and provide a variety of arithmetic operations on them. // //===----------------------------------------------------------------------===// #include "llvm/ADT/APFloat.h" #include "llvm/ADT/APSInt.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/MathExtras.h" #include <limits.h> #include <cstring> using namespace llvm; #define convolve(lhs, rhs) ((lhs) * 4 + (rhs)) /* Assumed in hexadecimal significand parsing, and conversion to hexadecimal strings. */ #define COMPILE_TIME_ASSERT(cond) extern int CTAssert[(cond) ? 1 : -1] COMPILE_TIME_ASSERT(integerPartWidth % 4 == 0); namespace llvm { /* Represents floating point arithmetic semantics. */ struct fltSemantics { /* The largest E such that 2^E is representable; this matches the definition of IEEE 754. */ exponent_t maxExponent; /* The smallest E such that 2^E is a normalized number; this matches the definition of IEEE 754. */ exponent_t minExponent; /* Number of bits in the significand. This includes the integer bit. */ unsigned int precision; /* True if arithmetic is supported. */ unsigned int arithmeticOK; }; const fltSemantics APFloat::IEEEhalf = { 15, -14, 11, true }; const fltSemantics APFloat::IEEEsingle = { 127, -126, 24, true }; const fltSemantics APFloat::IEEEdouble = { 1023, -1022, 53, true }; const fltSemantics APFloat::IEEEquad = { 16383, -16382, 113, true }; const fltSemantics APFloat::x87DoubleExtended = { 16383, -16382, 64, true }; const fltSemantics APFloat::Bogus = { 0, 0, 0, true }; // The PowerPC format consists of two doubles. It does not map cleanly // onto the usual format above. For now only storage of constants of // this type is supported, no arithmetic. const fltSemantics APFloat::PPCDoubleDouble = { 1023, -1022, 106, false }; /* A tight upper bound on number of parts required to hold the value pow(5, power) is power * 815 / (351 * integerPartWidth) + 1 However, whilst the result may require only this many parts, because we are multiplying two values to get it, the multiplication may require an extra part with the excess part being zero (consider the trivial case of 1 * 1, tcFullMultiply requires two parts to hold the single-part result). So we add an extra one to guarantee enough space whilst multiplying. */ const unsigned int maxExponent = 16383; const unsigned int maxPrecision = 113; const unsigned int maxPowerOfFiveExponent = maxExponent + maxPrecision - 1; const unsigned int maxPowerOfFiveParts = 2 + ((maxPowerOfFiveExponent * 815) / (351 * integerPartWidth)); } /* A bunch of private, handy routines. */ static inline unsigned int partCountForBits(unsigned int bits) { return ((bits) + integerPartWidth - 1) / integerPartWidth; } /* Returns 0U-9U. Return values >= 10U are not digits. */ static inline unsigned int decDigitValue(unsigned int c) { return c - '0'; } static unsigned int hexDigitValue(unsigned int c) { unsigned int r; r = c - '0'; if (r <= 9) return r; r = c - 'A'; if (r <= 5) return r + 10; r = c - 'a'; if (r <= 5) return r + 10; return -1U; } static inline void assertArithmeticOK(const llvm::fltSemantics &semantics) { assert(semantics.arithmeticOK && "Compile-time arithmetic does not support these semantics"); } /* Return the value of a decimal exponent of the form [+-]ddddddd. If the exponent overflows, returns a large exponent with the appropriate sign. */ static int readExponent(StringRef::iterator begin, StringRef::iterator end) { bool isNegative; unsigned int absExponent; const unsigned int overlargeExponent = 24000; /* FIXME. */ StringRef::iterator p = begin; assert(p != end && "Exponent has no digits"); isNegative = (*p == '-'); if (*p == '-' || *p == '+') { p++; assert(p != end && "Exponent has no digits"); } absExponent = decDigitValue(*p++); assert(absExponent < 10U && "Invalid character in exponent"); for (; p != end; ++p) { unsigned int value; value = decDigitValue(*p); assert(value < 10U && "Invalid character in exponent"); value += absExponent * 10; if (absExponent >= overlargeExponent) { absExponent = overlargeExponent; p = end; /* outwit assert below */ break; } absExponent = value; } assert(p == end && "Invalid exponent in exponent"); if (isNegative) return -(int) absExponent; else return (int) absExponent; } /* This is ugly and needs cleaning up, but I don't immediately see how whilst remaining safe. */ static int totalExponent(StringRef::iterator p, StringRef::iterator end, int exponentAdjustment) { int unsignedExponent; bool negative, overflow; int exponent = 0; assert(p != end && "Exponent has no digits"); negative = *p == '-'; if (*p == '-' || *p == '+') { p++; assert(p != end && "Exponent has no digits"); } unsignedExponent = 0; overflow = false; for (; p != end; ++p) { unsigned int value; value = decDigitValue(*p); assert(value < 10U && "Invalid character in exponent"); unsignedExponent = unsignedExponent * 10 + value; if (unsignedExponent > 32767) overflow = true; } if (exponentAdjustment > 32767 || exponentAdjustment < -32768) overflow = true; if (!overflow) { exponent = unsignedExponent; if (negative) exponent = -exponent; exponent += exponentAdjustment; if (exponent > 32767 || exponent < -32768) overflow = true; } if (overflow) exponent = negative ? -32768: 32767; return exponent; } static StringRef::iterator skipLeadingZeroesAndAnyDot(StringRef::iterator begin, StringRef::iterator end, StringRef::iterator *dot) { StringRef::iterator p = begin; *dot = end; while (*p == '0' && p != end) p++; if (*p == '.') { *dot = p++; assert(end - begin != 1 && "Significand has no digits"); while (*p == '0' && p != end) p++; } return p; } /* Given a normal decimal floating point number of the form dddd.dddd[eE][+-]ddd where the decimal point and exponent are optional, fill out the structure D. Exponent is appropriate if the significand is treated as an integer, and normalizedExponent if the significand is taken to have the decimal point after a single leading non-zero digit. If the value is zero, V->firstSigDigit points to a non-digit, and the return exponent is zero. */ struct decimalInfo { const char *firstSigDigit; const char *lastSigDigit; int exponent; int normalizedExponent; }; static void interpretDecimal(StringRef::iterator begin, StringRef::iterator end, decimalInfo *D) { StringRef::iterator dot = end; StringRef::iterator p = skipLeadingZeroesAndAnyDot (begin, end, &dot); D->firstSigDigit = p; D->exponent = 0; D->normalizedExponent = 0; for (; p != end; ++p) { if (*p == '.') { assert(dot == end && "String contains multiple dots"); dot = p++; if (p == end) break; } if (decDigitValue(*p) >= 10U) break; } if (p != end) { assert((*p == 'e' || *p == 'E') && "Invalid character in significand"); assert(p != begin && "Significand has no digits"); assert((dot == end || p - begin != 1) && "Significand has no digits"); /* p points to the first non-digit in the string */ D->exponent = readExponent(p + 1, end); /* Implied decimal point? */ if (dot == end) dot = p; } /* If number is all zeroes accept any exponent. */ if (p != D->firstSigDigit) { /* Drop insignificant trailing zeroes. */ if (p != begin) { do do p--; while (p != begin && *p == '0'); while (p != begin && *p == '.'); } /* Adjust the exponents for any decimal point. */ D->exponent += static_cast<exponent_t>((dot - p) - (dot > p)); D->normalizedExponent = (D->exponent + static_cast<exponent_t>((p - D->firstSigDigit) - (dot > D->firstSigDigit && dot < p))); } D->lastSigDigit = p; } /* Return the trailing fraction of a hexadecimal number. DIGITVALUE is the first hex digit of the fraction, P points to the next digit. */ static lostFraction trailingHexadecimalFraction(StringRef::iterator p, StringRef::iterator end, unsigned int digitValue) { unsigned int hexDigit; /* If the first trailing digit isn't 0 or 8 we can work out the fraction immediately. */ if (digitValue > 8) return lfMoreThanHalf; else if (digitValue < 8 && digitValue > 0) return lfLessThanHalf; /* Otherwise we need to find the first non-zero digit. */ while (*p == '0') p++; assert(p != end && "Invalid trailing hexadecimal fraction!"); hexDigit = hexDigitValue(*p); /* If we ran off the end it is exactly zero or one-half, otherwise a little more. */ if (hexDigit == -1U) return digitValue == 0 ? lfExactlyZero: lfExactlyHalf; else return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf; } /* Return the fraction lost were a bignum truncated losing the least significant BITS bits. */ static lostFraction lostFractionThroughTruncation(const integerPart *parts, unsigned int partCount, unsigned int bits) { unsigned int lsb; lsb = APInt::tcLSB(parts, partCount); /* Note this is guaranteed true if bits == 0, or LSB == -1U. */ if (bits <= lsb) return lfExactlyZero; if (bits == lsb + 1) return lfExactlyHalf; if (bits <= partCount * integerPartWidth && APInt::tcExtractBit(parts, bits - 1)) return lfMoreThanHalf; return lfLessThanHalf; } /* Shift DST right BITS bits noting lost fraction. */ static lostFraction shiftRight(integerPart *dst, unsigned int parts, unsigned int bits) { lostFraction lost_fraction; lost_fraction = lostFractionThroughTruncation(dst, parts, bits); APInt::tcShiftRight(dst, parts, bits); return lost_fraction; } /* Combine the effect of two lost fractions. */ static lostFraction combineLostFractions(lostFraction moreSignificant, lostFraction lessSignificant) { if (lessSignificant != lfExactlyZero) { if (moreSignificant == lfExactlyZero) moreSignificant = lfLessThanHalf; else if (moreSignificant == lfExactlyHalf) moreSignificant = lfMoreThanHalf; } return moreSignificant; } /* The error from the true value, in half-ulps, on multiplying two floating point numbers, which differ from the value they approximate by at most HUE1 and HUE2 half-ulps, is strictly less than the returned value. See "How to Read Floating Point Numbers Accurately" by William D Clinger. */ static unsigned int HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2) { assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8)); if (HUerr1 + HUerr2 == 0) return inexactMultiply * 2; /* <= inexactMultiply half-ulps. */ else return inexactMultiply + 2 * (HUerr1 + HUerr2); } /* The number of ulps from the boundary (zero, or half if ISNEAREST) when the least significant BITS are truncated. BITS cannot be zero. */ static integerPart ulpsFromBoundary(const integerPart *parts, unsigned int bits, bool isNearest) { unsigned int count, partBits; integerPart part, boundary; assert(bits != 0); bits--; count = bits / integerPartWidth; partBits = bits % integerPartWidth + 1; part = parts[count] & (~(integerPart) 0 >> (integerPartWidth - partBits)); if (isNearest) boundary = (integerPart) 1 << (partBits - 1); else boundary = 0; if (count == 0) { if (part - boundary <= boundary - part) return part - boundary; else return boundary - part; } if (part == boundary) { while (--count) if (parts[count]) return ~(integerPart) 0; /* A lot. */ return parts[0]; } else if (part == boundary - 1) { while (--count) if (~parts[count]) return ~(integerPart) 0; /* A lot. */ return -parts[0]; } return ~(integerPart) 0; /* A lot. */ } /* Place pow(5, power) in DST, and return the number of parts used. DST must be at least one part larger than size of the answer. */ static unsigned int powerOf5(integerPart *dst, unsigned int power) { static const integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125, 15625, 78125 }; integerPart pow5s[maxPowerOfFiveParts * 2 + 5]; pow5s[0] = 78125 * 5; unsigned int partsCount[16] = { 1 }; integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5; unsigned int result; assert(power <= maxExponent); p1 = dst; p2 = scratch; *p1 = firstEightPowers[power & 7]; power >>= 3; result = 1; pow5 = pow5s; for (unsigned int n = 0; power; power >>= 1, n++) { unsigned int pc; pc = partsCount[n]; /* Calculate pow(5,pow(2,n+3)) if we haven't yet. */ if (pc == 0) { pc = partsCount[n - 1]; APInt::tcFullMultiply(pow5, pow5 - pc, pow5 - pc, pc, pc); pc *= 2; if (pow5[pc - 1] == 0) pc--; partsCount[n] = pc; } if (power & 1) { integerPart *tmp; APInt::tcFullMultiply(p2, p1, pow5, result, pc); result += pc; if (p2[result - 1] == 0) result--; /* Now result is in p1 with partsCount parts and p2 is scratch space. */ tmp = p1, p1 = p2, p2 = tmp; } pow5 += pc; } if (p1 != dst) APInt::tcAssign(dst, p1, result); return result; } /* Zero at the end to avoid modular arithmetic when adding one; used when rounding up during hexadecimal output. */ static const char hexDigitsLower[] = "0123456789abcdef0"; static const char hexDigitsUpper[] = "0123456789ABCDEF0"; static const char infinityL[] = "infinity"; static const char infinityU[] = "INFINITY"; static const char NaNL[] = "nan"; static const char NaNU[] = "NAN"; /* Write out an integerPart in hexadecimal, starting with the most significant nibble. Write out exactly COUNT hexdigits, return COUNT. */ static unsigned int partAsHex (char *dst, integerPart part, unsigned int count, const char *hexDigitChars) { unsigned int result = count; assert(count != 0 && count <= integerPartWidth / 4); part >>= (integerPartWidth - 4 * count); while (count--) { dst[count] = hexDigitChars[part & 0xf]; part >>= 4; } return result; } /* Write out an unsigned decimal integer. */ static char * writeUnsignedDecimal (char *dst, unsigned int n) { char buff[40], *p; p = buff; do *p++ = '0' + n % 10; while (n /= 10); do *dst++ = *--p; while (p != buff); return dst; } /* Write out a signed decimal integer. */ static char * writeSignedDecimal (char *dst, int value) { if (value < 0) { *dst++ = '-'; dst = writeUnsignedDecimal(dst, -(unsigned) value); } else dst = writeUnsignedDecimal(dst, value); return dst; } /* Constructors. */ void APFloat::initialize(const fltSemantics *ourSemantics) { unsigned int count; semantics = ourSemantics; count = partCount(); if (count > 1) significand.parts = new integerPart[count]; } void APFloat::freeSignificand() { if (partCount() > 1) delete [] significand.parts; } void APFloat::assign(const APFloat &rhs) { assert(semantics == rhs.semantics); sign = rhs.sign; category = rhs.category; exponent = rhs.exponent; sign2 = rhs.sign2; exponent2 = rhs.exponent2; if (category == fcNormal || category == fcNaN) copySignificand(rhs); } void APFloat::copySignificand(const APFloat &rhs) { assert(category == fcNormal || category == fcNaN); assert(rhs.partCount() >= partCount()); APInt::tcAssign(significandParts(), rhs.significandParts(), partCount()); } /* Make this number a NaN, with an arbitrary but deterministic value for the significand. If double or longer, this is a signalling NaN, which may not be ideal. If float, this is QNaN(0). */ void APFloat::makeNaN(bool SNaN, bool Negative, const APInt *fill) { category = fcNaN; sign = Negative; integerPart *significand = significandParts(); unsigned numParts = partCount(); // Set the significand bits to the fill. if (!fill || fill->getNumWords() < numParts) APInt::tcSet(significand, 0, numParts); if (fill) { APInt::tcAssign(significand, fill->getRawData(), std::min(fill->getNumWords(), numParts)); // Zero out the excess bits of the significand. unsigned bitsToPreserve = semantics->precision - 1; unsigned part = bitsToPreserve / 64; bitsToPreserve %= 64; significand[part] &= ((1ULL << bitsToPreserve) - 1); for (part++; part != numParts; ++part) significand[part] = 0; } unsigned QNaNBit = semantics->precision - 2; if (SNaN) { // We always have to clear the QNaN bit to make it an SNaN. APInt::tcClearBit(significand, QNaNBit); // If there are no bits set in the payload, we have to set // *something* to make it a NaN instead of an infinity; // conventionally, this is the next bit down from the QNaN bit. if (APInt::tcIsZero(significand, numParts)) APInt::tcSetBit(significand, QNaNBit - 1); } else { // We always have to set the QNaN bit to make it a QNaN. APInt::tcSetBit(significand, QNaNBit); } // For x87 extended precision, we want to make a NaN, not a // pseudo-NaN. Maybe we should expose the ability to make // pseudo-NaNs? if (semantics == &APFloat::x87DoubleExtended) APInt::tcSetBit(significand, QNaNBit + 1); } APFloat APFloat::makeNaN(const fltSemantics &Sem, bool SNaN, bool Negative, const APInt *fill) { APFloat value(Sem, uninitialized); value.makeNaN(SNaN, Negative, fill); return value; } APFloat & APFloat::operator=(const APFloat &rhs) { if (this != &rhs) { if (semantics != rhs.semantics) { freeSignificand(); initialize(rhs.semantics); } assign(rhs); } return *this; } bool APFloat::bitwiseIsEqual(const APFloat &rhs) const { if (this == &rhs) return true; if (semantics != rhs.semantics || category != rhs.category || sign != rhs.sign) return false; if (semantics==(const llvm::fltSemantics*)&PPCDoubleDouble && sign2 != rhs.sign2) return false; if (category==fcZero || category==fcInfinity) return true; else if (category==fcNormal && exponent!=rhs.exponent) return false; else if (semantics==(const llvm::fltSemantics*)&PPCDoubleDouble && exponent2!=rhs.exponent2) return false; else { int i= partCount(); const integerPart* p=significandParts(); const integerPart* q=rhs.significandParts(); for (; i>0; i--, p++, q++) { if (*p != *q) return false; } return true; } } APFloat::APFloat(const fltSemantics &ourSemantics, integerPart value) : exponent2(0), sign2(0) { assertArithmeticOK(ourSemantics); initialize(&ourSemantics); sign = 0; zeroSignificand(); exponent = ourSemantics.precision - 1; significandParts()[0] = value; normalize(rmNearestTiesToEven, lfExactlyZero); } APFloat::APFloat(const fltSemantics &ourSemantics) : exponent2(0), sign2(0) { assertArithmeticOK(ourSemantics); initialize(&ourSemantics); category = fcZero; sign = false; } APFloat::APFloat(const fltSemantics &ourSemantics, uninitializedTag tag) : exponent2(0), sign2(0) { assertArithmeticOK(ourSemantics); // Allocates storage if necessary but does not initialize it. initialize(&ourSemantics); } APFloat::APFloat(const fltSemantics &ourSemantics, fltCategory ourCategory, bool negative) : exponent2(0), sign2(0) { assertArithmeticOK(ourSemantics); initialize(&ourSemantics); category = ourCategory; sign = negative; if (category == fcNormal) category = fcZero; else if (ourCategory == fcNaN) makeNaN(); } APFloat::APFloat(const fltSemantics &ourSemantics, StringRef text) : exponent2(0), sign2(0) { assertArithmeticOK(ourSemantics); initialize(&ourSemantics); convertFromString(text, rmNearestTiesToEven); } APFloat::APFloat(const APFloat &rhs) : exponent2(0), sign2(0) { initialize(rhs.semantics); assign(rhs); } APFloat::~APFloat() { freeSignificand(); } unsigned int APFloat::partCount() const { return partCountForBits(semantics->precision + 1); } unsigned int APFloat::semanticsPrecision(const fltSemantics &semantics) { return semantics.precision; } const integerPart * APFloat::significandParts() const { return const_cast<APFloat *>(this)->significandParts(); } integerPart * APFloat::significandParts() { assert(category == fcNormal || category == fcNaN); if (partCount() > 1) return significand.parts; else return &significand.part; } void APFloat::zeroSignificand() { category = fcNormal; APInt::tcSet(significandParts(), 0, partCount()); } /* Increment an fcNormal floating point number's significand. */ void APFloat::incrementSignificand() { integerPart carry; carry = APInt::tcIncrement(significandParts(), partCount()); /* Our callers should never cause us to overflow. */ assert(carry == 0); (void)carry; } /* Add the significand of the RHS. Returns the carry flag. */ integerPart APFloat::addSignificand(const APFloat &rhs) { integerPart *parts; parts = significandParts(); assert(semantics == rhs.semantics); assert(exponent == rhs.exponent); return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount()); } /* Subtract the significand of the RHS with a borrow flag. Returns the borrow flag. */ integerPart APFloat::subtractSignificand(const APFloat &rhs, integerPart borrow) { integerPart *parts; parts = significandParts(); assert(semantics == rhs.semantics); assert(exponent == rhs.exponent); return APInt::tcSubtract(parts, rhs.significandParts(), borrow, partCount()); } /* Multiply the significand of the RHS. If ADDEND is non-NULL, add it on to the full-precision result of the multiplication. Returns the lost fraction. */ lostFraction APFloat::multiplySignificand(const APFloat &rhs, const APFloat *addend) { unsigned int omsb; // One, not zero, based MSB. unsigned int partsCount, newPartsCount, precision; integerPart *lhsSignificand; integerPart scratch[4]; integerPart *fullSignificand; lostFraction lost_fraction; bool ignored; assert(semantics == rhs.semantics); precision = semantics->precision; newPartsCount = partCountForBits(precision * 2); if (newPartsCount > 4) fullSignificand = new integerPart[newPartsCount]; else fullSignificand = scratch; lhsSignificand = significandParts(); partsCount = partCount(); APInt::tcFullMultiply(fullSignificand, lhsSignificand, rhs.significandParts(), partsCount, partsCount); lost_fraction = lfExactlyZero; omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1; exponent += rhs.exponent; if (addend) { Significand savedSignificand = significand; const fltSemantics *savedSemantics = semantics; fltSemantics extendedSemantics; opStatus status; unsigned int extendedPrecision; /* Normalize our MSB. */ extendedPrecision = precision + precision - 1; if (omsb != extendedPrecision) { APInt::tcShiftLeft(fullSignificand, newPartsCount, extendedPrecision - omsb); exponent -= extendedPrecision - omsb; } /* Create new semantics. */ extendedSemantics = *semantics; extendedSemantics.precision = extendedPrecision; if (newPartsCount == 1) significand.part = fullSignificand[0]; else significand.parts = fullSignificand; semantics = &extendedSemantics; APFloat extendedAddend(*addend); status = extendedAddend.convert(extendedSemantics, rmTowardZero, &ignored); assert(status == opOK); (void)status; lost_fraction = addOrSubtractSignificand(extendedAddend, false); /* Restore our state. */ if (newPartsCount == 1) fullSignificand[0] = significand.part; significand = savedSignificand; semantics = savedSemantics; omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1; } exponent -= (precision - 1); if (omsb > precision) { unsigned int bits, significantParts; lostFraction lf; bits = omsb - precision; significantParts = partCountForBits(omsb); lf = shiftRight(fullSignificand, significantParts, bits); lost_fraction = combineLostFractions(lf, lost_fraction); exponent += bits; } APInt::tcAssign(lhsSignificand, fullSignificand, partsCount); if (newPartsCount > 4) delete [] fullSignificand; return lost_fraction; } /* Multiply the significands of LHS and RHS to DST. */ lostFraction APFloat::divideSignificand(const APFloat &rhs) { unsigned int bit, i, partsCount; const integerPart *rhsSignificand; integerPart *lhsSignificand, *dividend, *divisor; integerPart scratch[4]; lostFraction lost_fraction; assert(semantics == rhs.semantics); lhsSignificand = significandParts(); rhsSignificand = rhs.significandParts(); partsCount = partCount(); if (partsCount > 2) dividend = new integerPart[partsCount * 2]; else dividend = scratch; divisor = dividend + partsCount; /* Copy the dividend and divisor as they will be modified in-place. */ for (i = 0; i < partsCount; i++) { dividend[i] = lhsSignificand[i]; divisor[i] = rhsSignificand[i]; lhsSignificand[i] = 0; } exponent -= rhs.exponent; unsigned int precision = semantics->precision; /* Normalize the divisor. */ bit = precision - APInt::tcMSB(divisor, partsCount) - 1; if (bit) { exponent += bit; APInt::tcShiftLeft(divisor, partsCount, bit); } /* Normalize the dividend. */ bit = precision - APInt::tcMSB(dividend, partsCount) - 1; if (bit) { exponent -= bit; APInt::tcShiftLeft(dividend, partsCount, bit); } /* Ensure the dividend >= divisor initially for the loop below. Incidentally, this means that the division loop below is guaranteed to set the integer bit to one. */ if (APInt::tcCompare(dividend, divisor, partsCount) < 0) { exponent--; APInt::tcShiftLeft(dividend, partsCount, 1); assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0); } /* Long division. */ for (bit = precision; bit; bit -= 1) { if (APInt::tcCompare(dividend, divisor, partsCount) >= 0) { APInt::tcSubtract(dividend, divisor, 0, partsCount); APInt::tcSetBit(lhsSignificand, bit - 1); } APInt::tcShiftLeft(dividend, partsCount, 1); } /* Figure out the lost fraction. */ int cmp = APInt::tcCompare(dividend, divisor, partsCount); if (cmp > 0) lost_fraction = lfMoreThanHalf; else if (cmp == 0) lost_fraction = lfExactlyHalf; else if (APInt::tcIsZero(dividend, partsCount)) lost_fraction = lfExactlyZero; else lost_fraction = lfLessThanHalf; if (partsCount > 2) delete [] dividend; return lost_fraction; } unsigned int APFloat::significandMSB() const { return APInt::tcMSB(significandParts(), partCount()); } unsigned int APFloat::significandLSB() const { return APInt::tcLSB(significandParts(), partCount()); } /* Note that a zero result is NOT normalized to fcZero. */ lostFraction APFloat::shiftSignificandRight(unsigned int bits) { /* Our exponent should not overflow. */ assert((exponent_t) (exponent + bits) >= exponent); exponent += bits; return shiftRight(significandParts(), partCount(), bits); } /* Shift the significand left BITS bits, subtract BITS from its exponent. */ void APFloat::shiftSignificandLeft(unsigned int bits) { assert(bits < semantics->precision); if (bits) { unsigned int partsCount = partCount(); APInt::tcShiftLeft(significandParts(), partsCount, bits); exponent -= bits; assert(!APInt::tcIsZero(significandParts(), partsCount)); } } APFloat::cmpResult APFloat::compareAbsoluteValue(const APFloat &rhs) const { int compare; assert(semantics == rhs.semantics); assert(category == fcNormal); assert(rhs.category == fcNormal); compare = exponent - rhs.exponent; /* If exponents are equal, do an unsigned bignum comparison of the significands. */ if (compare == 0) compare = APInt::tcCompare(significandParts(), rhs.significandParts(), partCount()); if (compare > 0) return cmpGreaterThan; else if (compare < 0) return cmpLessThan; else return cmpEqual; } /* Handle overflow. Sign is preserved. We either become infinity or the largest finite number. */ APFloat::opStatus APFloat::handleOverflow(roundingMode rounding_mode) { /* Infinity? */ if (rounding_mode == rmNearestTiesToEven || rounding_mode == rmNearestTiesToAway || (rounding_mode == rmTowardPositive && !sign) || (rounding_mode == rmTowardNegative && sign)) { category = fcInfinity; return (opStatus) (opOverflow | opInexact); } /* Otherwise we become the largest finite number. */ category = fcNormal; exponent = semantics->maxExponent; APInt::tcSetLeastSignificantBits(significandParts(), partCount(), semantics->precision); return opInexact; } /* Returns TRUE if, when truncating the current number, with BIT the new LSB, with the given lost fraction and rounding mode, the result would need to be rounded away from zero (i.e., by increasing the signficand). This routine must work for fcZero of both signs, and fcNormal numbers. */ bool APFloat::roundAwayFromZero(roundingMode rounding_mode, lostFraction lost_fraction, unsigned int bit) const { /* NaNs and infinities should not have lost fractions. */ assert(category == fcNormal || category == fcZero); /* Current callers never pass this so we don't handle it. */ assert(lost_fraction != lfExactlyZero); switch (rounding_mode) { default: abort(); case rmNearestTiesToAway: return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf; case rmNearestTiesToEven: if (lost_fraction == lfMoreThanHalf) return true; /* Our zeroes don't have a significand to test. */ if (lost_fraction == lfExactlyHalf && category != fcZero) return APInt::tcExtractBit(significandParts(), bit); return false; case rmTowardZero: return false; case rmTowardPositive: return sign == false; case rmTowardNegative: return sign == true; } } APFloat::opStatus APFloat::normalize(roundingMode rounding_mode, lostFraction lost_fraction) { unsigned int omsb; /* One, not zero, based MSB. */ int exponentChange; if (category != fcNormal) return opOK; /* Before rounding normalize the exponent of fcNormal numbers. */ omsb = significandMSB() + 1; if (omsb) { /* OMSB is numbered from 1. We want to place it in the integer bit numbered PRECISON if possible, with a compensating change in the exponent. */ exponentChange = omsb - semantics->precision; /* If the resulting exponent is too high, overflow according to the rounding mode. */ if (exponent + exponentChange > semantics->maxExponent) return handleOverflow(rounding_mode); /* Subnormal numbers have exponent minExponent, and their MSB is forced based on that. */ if (exponent + exponentChange < semantics->minExponent) exponentChange = semantics->minExponent - exponent; /* Shifting left is easy as we don't lose precision. */ if (exponentChange < 0) { assert(lost_fraction == lfExactlyZero); shiftSignificandLeft(-exponentChange); return opOK; } if (exponentChange > 0) { lostFraction lf; /* Shift right and capture any new lost fraction. */ lf = shiftSignificandRight(exponentChange); lost_fraction = combineLostFractions(lf, lost_fraction); /* Keep OMSB up-to-date. */ if (omsb > (unsigned) exponentChange) omsb -= exponentChange; else omsb = 0; } } /* Now round the number according to rounding_mode given the lost fraction. */ /* As specified in IEEE 754, since we do not trap we do not report underflow for exact results. */ if (lost_fraction == lfExactlyZero) { /* Canonicalize zeroes. */ if (omsb == 0) category = fcZero; return opOK; } /* Increment the significand if we're rounding away from zero. */ if (roundAwayFromZero(rounding_mode, lost_fraction, 0)) { if (omsb == 0) exponent = semantics->minExponent; incrementSignificand(); omsb = significandMSB() + 1; /* Did the significand increment overflow? */ if (omsb == (unsigned) semantics->precision + 1) { /* Renormalize by incrementing the exponent and shifting our significand right one. However if we already have the maximum exponent we overflow to infinity. */ if (exponent == semantics->maxExponent) { category = fcInfinity; return (opStatus) (opOverflow | opInexact); } shiftSignificandRight(1); return opInexact; } } /* The normal case - we were and are not denormal, and any significand increment above didn't overflow. */ if (omsb == semantics->precision) return opInexact; /* We have a non-zero denormal. */ assert(omsb < semantics->precision); /* Canonicalize zeroes. */ if (omsb == 0) category = fcZero; /* The fcZero case is a denormal that underflowed to zero. */ return (opStatus) (opUnderflow | opInexact); } APFloat::opStatus APFloat::addOrSubtractSpecials(const APFloat &rhs, bool subtract) { switch (convolve(category, rhs.category)) { default: abort(); case convolve(fcNaN, fcZero): case convolve(fcNaN, fcNormal): case convolve(fcNaN, fcInfinity): case convolve(fcNaN, fcNaN): case convolve(fcNormal, fcZero): case convolve(fcInfinity, fcNormal): case convolve(fcInfinity, fcZero): return opOK; case convolve(fcZero, fcNaN): case convolve(fcNormal, fcNaN): case convolve(fcInfinity, fcNaN): category = fcNaN; copySignificand(rhs); return opOK; case convolve(fcNormal, fcInfinity): case convolve(fcZero, fcInfinity): category = fcInfinity; sign = rhs.sign ^ subtract; return opOK; case convolve(fcZero, fcNormal): assign(rhs); sign = rhs.sign ^ subtract; return opOK; case convolve(fcZero, fcZero): /* Sign depends on rounding mode; handled by caller. */ return opOK; case convolve(fcInfinity, fcInfinity): /* Differently signed infinities can only be validly subtracted. */ if (((sign ^ rhs.sign)!=0) != subtract) { makeNaN(); return opInvalidOp; } return opOK; case convolve(fcNormal, fcNormal): return opDivByZero; } } /* Add or subtract two normal numbers. */ lostFraction APFloat::addOrSubtractSignificand(const APFloat &rhs, bool subtract) { integerPart carry; lostFraction lost_fraction; int bits; /* Determine if the operation on the absolute values is effectively an addition or subtraction. */ subtract ^= (sign ^ rhs.sign) ? true : false; /* Are we bigger exponent-wise than the RHS? */ bits = exponent - rhs.exponent; /* Subtraction is more subtle than one might naively expect. */ if (subtract) { APFloat temp_rhs(rhs); bool reverse; if (bits == 0) { reverse = compareAbsoluteValue(temp_rhs) == cmpLessThan; lost_fraction = lfExactlyZero; } else if (bits > 0) { lost_fraction = temp_rhs.shiftSignificandRight(bits - 1); shiftSignificandLeft(1); reverse = false; } else { lost_fraction = shiftSignificandRight(-bits - 1); temp_rhs.shiftSignificandLeft(1); reverse = true; } if (reverse) { carry = temp_rhs.subtractSignificand (*this, lost_fraction != lfExactlyZero); copySignificand(temp_rhs); sign = !sign; } else { carry = subtractSignificand (temp_rhs, lost_fraction != lfExactlyZero); } /* Invert the lost fraction - it was on the RHS and subtracted. */ if (lost_fraction == lfLessThanHalf) lost_fraction = lfMoreThanHalf; else if (lost_fraction == lfMoreThanHalf) lost_fraction = lfLessThanHalf; /* The code above is intended to ensure that no borrow is necessary. */ assert(!carry); (void)carry; } else { if (bits > 0) { APFloat temp_rhs(rhs); lost_fraction = temp_rhs.shiftSignificandRight(bits); carry = addSignificand(temp_rhs); } else { lost_fraction = shiftSignificandRight(-bits); carry = addSignificand(rhs); } /* We have a guard bit; generating a carry cannot happen. */ assert(!carry); (void)carry; } return lost_fraction; } APFloat::opStatus APFloat::multiplySpecials(const APFloat &rhs) { switch (convolve(category, rhs.category)) { default: abort(); case convolve(fcNaN, fcZero): case convolve(fcNaN, fcNormal): case convolve(fcNaN, fcInfinity): case convolve(fcNaN, fcNaN): return opOK; case convolve(fcZero, fcNaN): case convolve(fcNormal, fcNaN): case convolve(fcInfinity, fcNaN): category = fcNaN; copySignificand(rhs); return opOK; case convolve(fcNormal, fcInfinity): case convolve(fcInfinity, fcNormal): case convolve(fcInfinity, fcInfinity): category = fcInfinity; return opOK; case convolve(fcZero, fcNormal): case convolve(fcNormal, fcZero): case convolve(fcZero, fcZero): category = fcZero; return opOK; case convolve(fcZero, fcInfinity): case convolve(fcInfinity, fcZero): makeNaN(); return opInvalidOp; case convolve(fcNormal, fcNormal): return opOK; } } APFloat::opStatus APFloat::divideSpecials(const APFloat &rhs) { switch (convolve(category, rhs.category)) { default: abort(); case convolve(fcNaN, fcZero): case convolve(fcNaN, fcNormal): case convolve(fcNaN, fcInfinity): case convolve(fcNaN, fcNaN): case convolve(fcInfinity, fcZero): case convolve(fcInfinity, fcNormal): case convolve(fcZero, fcInfinity): case convolve(fcZero, fcNormal): return opOK; case convolve(fcZero, fcNaN): case convolve(fcNormal, fcNaN): case convolve(fcInfinity, fcNaN): category = fcNaN; copySignificand(rhs); return opOK; case convolve(fcNormal, fcInfinity): category = fcZero; return opOK; case convolve(fcNormal, fcZero): category = fcInfinity; return opDivByZero; case convolve(fcInfinity, fcInfinity): case convolve(fcZero, fcZero): makeNaN(); return opInvalidOp; case convolve(fcNormal, fcNormal): return opOK; } } APFloat::opStatus APFloat::modSpecials(const APFloat &rhs) { switch (convolve(category, rhs.category)) { default: abort(); case convolve(fcNaN, fcZero): case convolve(fcNaN, fcNormal): case convolve(fcNaN, fcInfinity): case convolve(fcNaN, fcNaN): case convolve(fcZero, fcInfinity): case convolve(fcZero, fcNormal): case convolve(fcNormal, fcInfinity): return opOK; case convolve(fcZero, fcNaN): case convolve(fcNormal, fcNaN): case convolve(fcInfinity, fcNaN): category = fcNaN; copySignificand(rhs); return opOK; case convolve(fcNormal, fcZero): case convolve(fcInfinity, fcZero): case convolve(fcInfinity, fcNormal): case convolve(fcInfinity, fcInfinity): case convolve(fcZero, fcZero): makeNaN(); return opInvalidOp; case convolve(fcNormal, fcNormal): return opOK; } } /* Change sign. */ void APFloat::changeSign() { /* Look mummy, this one's easy. */ sign = !sign; } void APFloat::clearSign() { /* So is this one. */ sign = 0; } void APFloat::copySign(const APFloat &rhs) { /* And this one. */ sign = rhs.sign; } /* Normalized addition or subtraction. */ APFloat::opStatus APFloat::addOrSubtract(const APFloat &rhs, roundingMode rounding_mode, bool subtract) { opStatus fs; assertArithmeticOK(*semantics); fs = addOrSubtractSpecials(rhs, subtract); /* This return code means it was not a simple case. */ if (fs == opDivByZero) { lostFraction lost_fraction; lost_fraction = addOrSubtractSignificand(rhs, subtract); fs = normalize(rounding_mode, lost_fraction); /* Can only be zero if we lost no fraction. */ assert(category != fcZero || lost_fraction == lfExactlyZero); } /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a positive zero unless rounding to minus infinity, except that adding two like-signed zeroes gives that zero. */ if (category == fcZero) { if (rhs.category != fcZero || (sign == rhs.sign) == subtract) sign = (rounding_mode == rmTowardNegative); } return fs; } /* Normalized addition. */ APFloat::opStatus APFloat::add(const APFloat &rhs, roundingMode rounding_mode) { return addOrSubtract(rhs, rounding_mode, false); } /* Normalized subtraction. */ APFloat::opStatus APFloat::subtract(const APFloat &rhs, roundingMode rounding_mode) { return addOrSubtract(rhs, rounding_mode, true); } /* Normalized multiply. */ APFloat::opStatus APFloat::multiply(const APFloat &rhs, roundingMode rounding_mode) { opStatus fs; assertArithmeticOK(*semantics); sign ^= rhs.sign; fs = multiplySpecials(rhs); if (category == fcNormal) { lostFraction lost_fraction = multiplySignificand(rhs, 0); fs = normalize(rounding_mode, lost_fraction); if (lost_fraction != lfExactlyZero) fs = (opStatus) (fs | opInexact); } return fs; } /* Normalized divide. */ APFloat::opStatus APFloat::divide(const APFloat &rhs, roundingMode rounding_mode) { opStatus fs; assertArithmeticOK(*semantics); sign ^= rhs.sign; fs = divideSpecials(rhs); if (category == fcNormal) { lostFraction lost_fraction = divideSignificand(rhs); fs = normalize(rounding_mode, lost_fraction); if (lost_fraction != lfExactlyZero) fs = (opStatus) (fs | opInexact); } return fs; } /* Normalized remainder. This is not currently correct in all cases. */ APFloat::opStatus APFloat::remainder(const APFloat &rhs) { opStatus fs; APFloat V = *this; unsigned int origSign = sign; assertArithmeticOK(*semantics); fs = V.divide(rhs, rmNearestTiesToEven); if (fs == opDivByZero) return fs; int parts = partCount(); integerPart *x = new integerPart[parts]; bool ignored; fs = V.convertToInteger(x, parts * integerPartWidth, true, rmNearestTiesToEven, &ignored); if (fs==opInvalidOp) return fs; fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true, rmNearestTiesToEven); assert(fs==opOK); // should always work fs = V.multiply(rhs, rmNearestTiesToEven); assert(fs==opOK || fs==opInexact); // should not overflow or underflow fs = subtract(V, rmNearestTiesToEven); assert(fs==opOK || fs==opInexact); // likewise if (isZero()) sign = origSign; // IEEE754 requires this delete[] x; return fs; } /* Normalized llvm frem (C fmod). This is not currently correct in all cases. */ APFloat::opStatus APFloat::mod(const APFloat &rhs, roundingMode rounding_mode) { opStatus fs; assertArithmeticOK(*semantics); fs = modSpecials(rhs); if (category == fcNormal && rhs.category == fcNormal) { APFloat V = *this; unsigned int origSign = sign; fs = V.divide(rhs, rmNearestTiesToEven); if (fs == opDivByZero) return fs; int parts = partCount(); integerPart *x = new integerPart[parts]; bool ignored; fs = V.convertToInteger(x, parts * integerPartWidth, true, rmTowardZero, &ignored); if (fs==opInvalidOp) return fs; fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true, rmNearestTiesToEven); assert(fs==opOK); // should always work fs = V.multiply(rhs, rounding_mode); assert(fs==opOK || fs==opInexact); // should not overflow or underflow fs = subtract(V, rounding_mode); assert(fs==opOK || fs==opInexact); // likewise if (isZero()) sign = origSign; // IEEE754 requires this delete[] x; } return fs; } /* Normalized fused-multiply-add. */ APFloat::opStatus APFloat::fusedMultiplyAdd(const APFloat &multiplicand, const APFloat &addend, roundingMode rounding_mode) { opStatus fs; assertArithmeticOK(*semantics); /* Post-multiplication sign, before addition. */ sign ^= multiplicand.sign; /* If and only if all arguments are normal do we need to do an extended-precision calculation. */ if (category == fcNormal && multiplicand.category == fcNormal && addend.category == fcNormal) { lostFraction lost_fraction; lost_fraction = multiplySignificand(multiplicand, &addend); fs = normalize(rounding_mode, lost_fraction); if (lost_fraction != lfExactlyZero) fs = (opStatus) (fs | opInexact); /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a positive zero unless rounding to minus infinity, except that adding two like-signed zeroes gives that zero. */ if (category == fcZero && sign != addend.sign) sign = (rounding_mode == rmTowardNegative); } else { fs = multiplySpecials(multiplicand); /* FS can only be opOK or opInvalidOp. There is no more work to do in the latter case. The IEEE-754R standard says it is implementation-defined in this case whether, if ADDEND is a quiet NaN, we raise invalid op; this implementation does so. If we need to do the addition we can do so with normal precision. */ if (fs == opOK) fs = addOrSubtract(addend, rounding_mode, false); } return fs; } /* Comparison requires normalized numbers. */ APFloat::cmpResult APFloat::compare(const APFloat &rhs) const { cmpResult result; assertArithmeticOK(*semantics); assert(semantics == rhs.semantics); switch (convolve(category, rhs.category)) { default: abort(); case convolve(fcNaN, fcZero): case convolve(fcNaN, fcNormal): case convolve(fcNaN, fcInfinity): case convolve(fcNaN, fcNaN): case convolve(fcZero, fcNaN): case convolve(fcNormal, fcNaN): case convolve(fcInfinity, fcNaN): return cmpUnordered; case convolve(fcInfinity, fcNormal): case convolve(fcInfinity, fcZero): case convolve(fcNormal, fcZero): if (sign) return cmpLessThan; else return cmpGreaterThan; case convolve(fcNormal, fcInfinity): case convolve(fcZero, fcInfinity): case convolve(fcZero, fcNormal): if (rhs.sign) return cmpGreaterThan; else return cmpLessThan; case convolve(fcInfinity, fcInfinity): if (sign == rhs.sign) return cmpEqual; else if (sign) return cmpLessThan; else return cmpGreaterThan; case convolve(fcZero, fcZero): return cmpEqual; case convolve(fcNormal, fcNormal): break; } /* Two normal numbers. Do they have the same sign? */ if (sign != rhs.sign) { if (sign) result = cmpLessThan; else result = cmpGreaterThan; } else { /* Compare absolute values; invert result if negative. */ result = compareAbsoluteValue(rhs); if (sign) { if (result == cmpLessThan) result = cmpGreaterThan; else if (result == cmpGreaterThan) result = cmpLessThan; } } return result; } /// APFloat::convert - convert a value of one floating point type to another. /// The return value corresponds to the IEEE754 exceptions. *losesInfo /// records whether the transformation lost information, i.e. whether /// converting the result back to the original type will produce the /// original value (this is almost the same as return value==fsOK, but there /// are edge cases where this is not so). APFloat::opStatus APFloat::convert(const fltSemantics &toSemantics, roundingMode rounding_mode, bool *losesInfo) { lostFraction lostFraction; unsigned int newPartCount, oldPartCount; opStatus fs; assertArithmeticOK(*semantics); assertArithmeticOK(toSemantics); lostFraction = lfExactlyZero; newPartCount = partCountForBits(toSemantics.precision + 1); oldPartCount = partCount(); /* Handle storage complications. If our new form is wider, re-allocate our bit pattern into wider storage. If it is narrower, we ignore the excess parts, but if narrowing to a single part we need to free the old storage. Be careful not to reference significandParts for zeroes and infinities, since it aborts. */ if (newPartCount > oldPartCount) { integerPart *newParts; newParts = new integerPart[newPartCount]; APInt::tcSet(newParts, 0, newPartCount); if (category==fcNormal || category==fcNaN) APInt::tcAssign(newParts, significandParts(), oldPartCount); freeSignificand(); significand.parts = newParts; } else if (newPartCount < oldPartCount) { /* Capture any lost fraction through truncation of parts so we get correct rounding whilst normalizing. */ if (category==fcNormal) lostFraction = lostFractionThroughTruncation (significandParts(), oldPartCount, toSemantics.precision); if (newPartCount == 1) { integerPart newPart = 0; if (category==fcNormal || category==fcNaN) newPart = significandParts()[0]; freeSignificand(); significand.part = newPart; } } if (category == fcNormal) { /* Re-interpret our bit-pattern. */ exponent += toSemantics.precision - semantics->precision; semantics = &toSemantics; fs = normalize(rounding_mode, lostFraction); *losesInfo = (fs != opOK); } else if (category == fcNaN) { int shift = toSemantics.precision - semantics->precision; // Do this now so significandParts gets the right answer const fltSemantics *oldSemantics = semantics; semantics = &toSemantics; *losesInfo = false; // No normalization here, just truncate if (shift>0) APInt::tcShiftLeft(significandParts(), newPartCount, shift); else if (shift < 0) { unsigned ushift = -shift; // Figure out if we are losing information. This happens // if are shifting out something other than 0s, or if the x87 long // double input did not have its integer bit set (pseudo-NaN), or if the // x87 long double input did not have its QNan bit set (because the x87 // hardware sets this bit when converting a lower-precision NaN to // x87 long double). if (APInt::tcLSB(significandParts(), newPartCount) < ushift) *losesInfo = true; if (oldSemantics == &APFloat::x87DoubleExtended && (!(*significandParts() & 0x8000000000000000ULL) || !(*significandParts() & 0x4000000000000000ULL))) *losesInfo = true; APInt::tcShiftRight(significandParts(), newPartCount, ushift); } // gcc forces the Quiet bit on, which means (float)(double)(float_sNan) // does not give you back the same bits. This is dubious, and we // don't currently do it. You're really supposed to get // an invalid operation signal at runtime, but nobody does that. fs = opOK; } else { semantics = &toSemantics; fs = opOK; *losesInfo = false; } return fs; } /* Convert a floating point number to an integer according to the rounding mode. If the rounded integer value is out of range this returns an invalid operation exception and the contents of the destination parts are unspecified. If the rounded value is in range but the floating point number is not the exact integer, the C standard doesn't require an inexact exception to be raised. IEEE 854 does require it so we do that. Note that for conversions to integer type the C standard requires round-to-zero to always be used. */ APFloat::opStatus APFloat::convertToSignExtendedInteger(integerPart *parts, unsigned int width, bool isSigned, roundingMode rounding_mode, bool *isExact) const { lostFraction lost_fraction; const integerPart *src; unsigned int dstPartsCount, truncatedBits; assertArithmeticOK(*semantics); *isExact = false; /* Handle the three special cases first. */ if (category == fcInfinity || category == fcNaN) return opInvalidOp; dstPartsCount = partCountForBits(width); if (category == fcZero) { APInt::tcSet(parts, 0, dstPartsCount); // Negative zero can't be represented as an int. *isExact = !sign; return opOK; } src = significandParts(); /* Step 1: place our absolute value, with any fraction truncated, in the destination. */ if (exponent < 0) { /* Our absolute value is less than one; truncate everything. */ APInt::tcSet(parts, 0, dstPartsCount); /* For exponent -1 the integer bit represents .5, look at that. For smaller exponents leftmost truncated bit is 0. */ truncatedBits = semantics->precision -1U - exponent; } else { /* We want the most significant (exponent + 1) bits; the rest are truncated. */ unsigned int bits = exponent + 1U; /* Hopelessly large in magnitude? */ if (bits > width) return opInvalidOp; if (bits < semantics->precision) { /* We truncate (semantics->precision - bits) bits. */ truncatedBits = semantics->precision - bits; APInt::tcExtract(parts, dstPartsCount, src, bits, truncatedBits); } else { /* We want at least as many bits as are available. */ APInt::tcExtract(parts, dstPartsCount, src, semantics->precision, 0); APInt::tcShiftLeft(parts, dstPartsCount, bits - semantics->precision); truncatedBits = 0; } } /* Step 2: work out any lost fraction, and increment the absolute value if we would round away from zero. */ if (truncatedBits) { lost_fraction = lostFractionThroughTruncation(src, partCount(), truncatedBits); if (lost_fraction != lfExactlyZero && roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) { if (APInt::tcIncrement(parts, dstPartsCount)) return opInvalidOp; /* Overflow. */ } } else { lost_fraction = lfExactlyZero; } /* Step 3: check if we fit in the destination. */ unsigned int omsb = APInt::tcMSB(parts, dstPartsCount) + 1; if (sign) { if (!isSigned) { /* Negative numbers cannot be represented as unsigned. */ if (omsb != 0) return opInvalidOp; } else { /* It takes omsb bits to represent the unsigned integer value. We lose a bit for the sign, but care is needed as the maximally negative integer is a special case. */ if (omsb == width && APInt::tcLSB(parts, dstPartsCount) + 1 != omsb) return opInvalidOp; /* This case can happen because of rounding. */ if (omsb > width) return opInvalidOp; } APInt::tcNegate (parts, dstPartsCount); } else { if (omsb >= width + !isSigned) return opInvalidOp; } if (lost_fraction == lfExactlyZero) { *isExact = true; return opOK; } else return opInexact; } /* Same as convertToSignExtendedInteger, except we provide deterministic values in case of an invalid operation exception, namely zero for NaNs and the minimal or maximal value respectively for underflow or overflow. The *isExact output tells whether the result is exact, in the sense that converting it back to the original floating point type produces the original value. This is almost equivalent to result==opOK, except for negative zeroes. */ APFloat::opStatus APFloat::convertToInteger(integerPart *parts, unsigned int width, bool isSigned, roundingMode rounding_mode, bool *isExact) const { opStatus fs; fs = convertToSignExtendedInteger(parts, width, isSigned, rounding_mode, isExact); if (fs == opInvalidOp) { unsigned int bits, dstPartsCount; dstPartsCount = partCountForBits(width); if (category == fcNaN) bits = 0; else if (sign) bits = isSigned; else bits = width - isSigned; APInt::tcSetLeastSignificantBits(parts, dstPartsCount, bits); if (sign && isSigned) APInt::tcShiftLeft(parts, dstPartsCount, width - 1); } return fs; } /* Same as convertToInteger(integerPart*, ...), except the result is returned in an APSInt, whose initial bit-width and signed-ness are used to determine the precision of the conversion. */ APFloat::opStatus APFloat::convertToInteger(APSInt &result, roundingMode rounding_mode, bool *isExact) const { unsigned bitWidth = result.getBitWidth(); SmallVector<uint64_t, 4> parts(result.getNumWords()); opStatus status = convertToInteger( parts.data(), bitWidth, result.isSigned(), rounding_mode, isExact); // Keeps the original signed-ness. result = APInt(bitWidth, parts); return status; } /* Convert an unsigned integer SRC to a floating point number, rounding according to ROUNDING_MODE. The sign of the floating point number is not modified. */ APFloat::opStatus APFloat::convertFromUnsignedParts(const integerPart *src, unsigned int srcCount, roundingMode rounding_mode) { unsigned int omsb, precision, dstCount; integerPart *dst; lostFraction lost_fraction; assertArithmeticOK(*semantics); category = fcNormal; omsb = APInt::tcMSB(src, srcCount) + 1; dst = significandParts(); dstCount = partCount(); precision = semantics->precision; /* We want the most significant PRECISON bits of SRC. There may not be that many; extract what we can. */ if (precision <= omsb) { exponent = omsb - 1; lost_fraction = lostFractionThroughTruncation(src, srcCount, omsb - precision); APInt::tcExtract(dst, dstCount, src, precision, omsb - precision); } else { exponent = precision - 1; lost_fraction = lfExactlyZero; APInt::tcExtract(dst, dstCount, src, omsb, 0); } return normalize(rounding_mode, lost_fraction); } APFloat::opStatus APFloat::convertFromAPInt(const APInt &Val, bool isSigned, roundingMode rounding_mode) { unsigned int partCount = Val.getNumWords(); APInt api = Val; sign = false; if (isSigned && api.isNegative()) { sign = true; api = -api; } return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode); } /* Convert a two's complement integer SRC to a floating point number, rounding according to ROUNDING_MODE. ISSIGNED is true if the integer is signed, in which case it must be sign-extended. */ APFloat::opStatus APFloat::convertFromSignExtendedInteger(const integerPart *src, unsigned int srcCount, bool isSigned, roundingMode rounding_mode) { opStatus status; assertArithmeticOK(*semantics); if (isSigned && APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) { integerPart *copy; /* If we're signed and negative negate a copy. */ sign = true; copy = new integerPart[srcCount]; APInt::tcAssign(copy, src, srcCount); APInt::tcNegate(copy, srcCount); status = convertFromUnsignedParts(copy, srcCount, rounding_mode); delete [] copy; } else { sign = false; status = convertFromUnsignedParts(src, srcCount, rounding_mode); } return status; } /* FIXME: should this just take a const APInt reference? */ APFloat::opStatus APFloat::convertFromZeroExtendedInteger(const integerPart *parts, unsigned int width, bool isSigned, roundingMode rounding_mode) { unsigned int partCount = partCountForBits(width); APInt api = APInt(width, makeArrayRef(parts, partCount)); sign = false; if (isSigned && APInt::tcExtractBit(parts, width - 1)) { sign = true; api = -api; } return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode); } APFloat::opStatus APFloat::convertFromHexadecimalString(StringRef s, roundingMode rounding_mode) { lostFraction lost_fraction = lfExactlyZero; integerPart *significand; unsigned int bitPos, partsCount; StringRef::iterator dot, firstSignificantDigit; zeroSignificand(); exponent = 0; category = fcNormal; significand = significandParts(); partsCount = partCount(); bitPos = partsCount * integerPartWidth; /* Skip leading zeroes and any (hexa)decimal point. */ StringRef::iterator begin = s.begin(); StringRef::iterator end = s.end(); StringRef::iterator p = skipLeadingZeroesAndAnyDot(begin, end, &dot); firstSignificantDigit = p; for (; p != end;) { integerPart hex_value; if (*p == '.') { assert(dot == end && "String contains multiple dots"); dot = p++; if (p == end) { break; } } hex_value = hexDigitValue(*p); if (hex_value == -1U) { break; } p++; if (p == end) { break; } else { /* Store the number whilst 4-bit nibbles remain. */ if (bitPos) { bitPos -= 4; hex_value <<= bitPos % integerPartWidth; significand[bitPos / integerPartWidth] |= hex_value; } else { lost_fraction = trailingHexadecimalFraction(p, end, hex_value); while (p != end && hexDigitValue(*p) != -1U) p++; break; } } } /* Hex floats require an exponent but not a hexadecimal point. */ assert(p != end && "Hex strings require an exponent"); assert((*p == 'p' || *p == 'P') && "Invalid character in significand"); assert(p != begin && "Significand has no digits"); assert((dot == end || p - begin != 1) && "Significand has no digits"); /* Ignore the exponent if we are zero. */ if (p != firstSignificantDigit) { int expAdjustment; /* Implicit hexadecimal point? */ if (dot == end) dot = p; /* Calculate the exponent adjustment implicit in the number of significant digits. */ expAdjustment = static_cast<int>(dot - firstSignificantDigit); if (expAdjustment < 0) expAdjustment++; expAdjustment = expAdjustment * 4 - 1; /* Adjust for writing the significand starting at the most significant nibble. */ expAdjustment += semantics->precision; expAdjustment -= partsCount * integerPartWidth; /* Adjust for the given exponent. */ exponent = totalExponent(p + 1, end, expAdjustment); } return normalize(rounding_mode, lost_fraction); } APFloat::opStatus APFloat::roundSignificandWithExponent(const integerPart *decSigParts, unsigned sigPartCount, int exp, roundingMode rounding_mode) { unsigned int parts, pow5PartCount; fltSemantics calcSemantics = { 32767, -32767, 0, true }; integerPart pow5Parts[maxPowerOfFiveParts]; bool isNearest; isNearest = (rounding_mode == rmNearestTiesToEven || rounding_mode == rmNearestTiesToAway); parts = partCountForBits(semantics->precision + 11); /* Calculate pow(5, abs(exp)). */ pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp: -exp); for (;; parts *= 2) { opStatus sigStatus, powStatus; unsigned int excessPrecision, truncatedBits; calcSemantics.precision = parts * integerPartWidth - 1; excessPrecision = calcSemantics.precision - semantics->precision; truncatedBits = excessPrecision; APFloat decSig(calcSemantics, fcZero, sign); APFloat pow5(calcSemantics, fcZero, false); sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount, rmNearestTiesToEven); powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount, rmNearestTiesToEven); /* Add exp, as 10^n = 5^n * 2^n. */ decSig.exponent += exp; lostFraction calcLostFraction; integerPart HUerr, HUdistance; unsigned int powHUerr; if (exp >= 0) { /* multiplySignificand leaves the precision-th bit set to 1. */ calcLostFraction = decSig.multiplySignificand(pow5, NULL); powHUerr = powStatus != opOK; } else { calcLostFraction = decSig.divideSignificand(pow5); /* Denormal numbers have less precision. */ if (decSig.exponent < semantics->minExponent) { excessPrecision += (semantics->minExponent - decSig.exponent); truncatedBits = excessPrecision; if (excessPrecision > calcSemantics.precision) excessPrecision = calcSemantics.precision; } /* Extra half-ulp lost in reciprocal of exponent. */ powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0:2; } /* Both multiplySignificand and divideSignificand return the result with the integer bit set. */ assert(APInt::tcExtractBit (decSig.significandParts(), calcSemantics.precision - 1) == 1); HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK, powHUerr); HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(), excessPrecision, isNearest); /* Are we guaranteed to round correctly if we truncate? */ if (HUdistance >= HUerr) { APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(), calcSemantics.precision - excessPrecision, excessPrecision); /* Take the exponent of decSig. If we tcExtract-ed less bits above we must adjust our exponent to compensate for the implicit right shift. */ exponent = (decSig.exponent + semantics->precision - (calcSemantics.precision - excessPrecision)); calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(), decSig.partCount(), truncatedBits); return normalize(rounding_mode, calcLostFraction); } } } APFloat::opStatus APFloat::convertFromDecimalString(StringRef str, roundingMode rounding_mode) { decimalInfo D; opStatus fs; /* Scan the text. */ StringRef::iterator p = str.begin(); interpretDecimal(p, str.end(), &D); /* Handle the quick cases. First the case of no significant digits, i.e. zero, and then exponents that are obviously too large or too small. Writing L for log 10 / log 2, a number d.ddddd*10^exp definitely overflows if (exp - 1) * L >= maxExponent and definitely underflows to zero where (exp + 1) * L <= minExponent - precision With integer arithmetic the tightest bounds for L are 93/28 < L < 196/59 [ numerator <= 256 ] 42039/12655 < L < 28738/8651 [ numerator <= 65536 ] */ if (decDigitValue(*D.firstSigDigit) >= 10U) { category = fcZero; fs = opOK; /* Check whether the normalized exponent is high enough to overflow max during the log-rebasing in the max-exponent check below. */ } else if (D.normalizedExponent - 1 > INT_MAX / 42039) { fs = handleOverflow(rounding_mode); /* If it wasn't, then it also wasn't high enough to overflow max during the log-rebasing in the min-exponent check. Check that it won't overflow min in either check, then perform the min-exponent check. */ } else if (D.normalizedExponent - 1 < INT_MIN / 42039 || (D.normalizedExponent + 1) * 28738 <= 8651 * (semantics->minExponent - (int) semantics->precision)) { /* Underflow to zero and round. */ zeroSignificand(); fs = normalize(rounding_mode, lfLessThanHalf); /* We can finally safely perform the max-exponent check. */ } else if ((D.normalizedExponent - 1) * 42039 >= 12655 * semantics->maxExponent) { /* Overflow and round. */ fs = handleOverflow(rounding_mode); } else { integerPart *decSignificand; unsigned int partCount; /* A tight upper bound on number of bits required to hold an N-digit decimal integer is N * 196 / 59. Allocate enough space to hold the full significand, and an extra part required by tcMultiplyPart. */ partCount = static_cast<unsigned int>(D.lastSigDigit - D.firstSigDigit) + 1; partCount = partCountForBits(1 + 196 * partCount / 59); decSignificand = new integerPart[partCount + 1]; partCount = 0; /* Convert to binary efficiently - we do almost all multiplication in an integerPart. When this would overflow do we do a single bignum multiplication, and then revert again to multiplication in an integerPart. */ do { integerPart decValue, val, multiplier; val = 0; multiplier = 1; do { if (*p == '.') { p++; if (p == str.end()) { break; } } decValue = decDigitValue(*p++); assert(decValue < 10U && "Invalid character in significand"); multiplier *= 10; val = val * 10 + decValue; /* The maximum number that can be multiplied by ten with any digit added without overflowing an integerPart. */ } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10); /* Multiply out the current part. */ APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val, partCount, partCount + 1, false); /* If we used another part (likely but not guaranteed), increase the count. */ if (decSignificand[partCount]) partCount++; } while (p <= D.lastSigDigit); category = fcNormal; fs = roundSignificandWithExponent(decSignificand, partCount, D.exponent, rounding_mode); delete [] decSignificand; } return fs; } APFloat::opStatus APFloat::convertFromString(StringRef str, roundingMode rounding_mode) { assertArithmeticOK(*semantics); assert(!str.empty() && "Invalid string length"); /* Handle a leading minus sign. */ StringRef::iterator p = str.begin(); size_t slen = str.size(); sign = *p == '-' ? 1 : 0; if (*p == '-' || *p == '+') { p++; slen--; assert(slen && "String has no digits"); } if (slen >= 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) { assert(slen - 2 && "Invalid string"); return convertFromHexadecimalString(StringRef(p + 2, slen - 2), rounding_mode); } return convertFromDecimalString(StringRef(p, slen), rounding_mode); } /* Write out a hexadecimal representation of the floating point value to DST, which must be of sufficient size, in the C99 form [-]0xh.hhhhp[+-]d. Return the number of characters written, excluding the terminating NUL. If UPPERCASE, the output is in upper case, otherwise in lower case. HEXDIGITS digits appear altogether, rounding the value if necessary. If HEXDIGITS is 0, the minimal precision to display the number precisely is used instead. If nothing would appear after the decimal point it is suppressed. The decimal exponent is always printed and has at least one digit. Zero values display an exponent of zero. Infinities and NaNs appear as "infinity" or "nan" respectively. The above rules are as specified by C99. There is ambiguity about what the leading hexadecimal digit should be. This implementation uses whatever is necessary so that the exponent is displayed as stored. This implies the exponent will fall within the IEEE format range, and the leading hexadecimal digit will be 0 (for denormals), 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with any other digits zero). */ unsigned int APFloat::convertToHexString(char *dst, unsigned int hexDigits, bool upperCase, roundingMode rounding_mode) const { char *p; assertArithmeticOK(*semantics); p = dst; if (sign) *dst++ = '-'; switch (category) { case fcInfinity: memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1); dst += sizeof infinityL - 1; break; case fcNaN: memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1); dst += sizeof NaNU - 1; break; case fcZero: *dst++ = '0'; *dst++ = upperCase ? 'X': 'x'; *dst++ = '0'; if (hexDigits > 1) { *dst++ = '.'; memset (dst, '0', hexDigits - 1); dst += hexDigits - 1; } *dst++ = upperCase ? 'P': 'p'; *dst++ = '0'; break; case fcNormal: dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode); break; } *dst = 0; return static_cast<unsigned int>(dst - p); } /* Does the hard work of outputting the correctly rounded hexadecimal form of a normal floating point number with the specified number of hexadecimal digits. If HEXDIGITS is zero the minimum number of digits necessary to print the value precisely is output. */ char * APFloat::convertNormalToHexString(char *dst, unsigned int hexDigits, bool upperCase, roundingMode rounding_mode) const { unsigned int count, valueBits, shift, partsCount, outputDigits; const char *hexDigitChars; const integerPart *significand; char *p; bool roundUp; *dst++ = '0'; *dst++ = upperCase ? 'X': 'x'; roundUp = false; hexDigitChars = upperCase ? hexDigitsUpper: hexDigitsLower; significand = significandParts(); partsCount = partCount(); /* +3 because the first digit only uses the single integer bit, so we have 3 virtual zero most-significant-bits. */ valueBits = semantics->precision + 3; shift = integerPartWidth - valueBits % integerPartWidth; /* The natural number of digits required ignoring trailing insignificant zeroes. */ outputDigits = (valueBits - significandLSB () + 3) / 4; /* hexDigits of zero means use the required number for the precision. Otherwise, see if we are truncating. If we are, find out if we need to round away from zero. */ if (hexDigits) { if (hexDigits < outputDigits) { /* We are dropping non-zero bits, so need to check how to round. "bits" is the number of dropped bits. */ unsigned int bits; lostFraction fraction; bits = valueBits - hexDigits * 4; fraction = lostFractionThroughTruncation (significand, partsCount, bits); roundUp = roundAwayFromZero(rounding_mode, fraction, bits); } outputDigits = hexDigits; } /* Write the digits consecutively, and start writing in the location of the hexadecimal point. We move the most significant digit left and add the hexadecimal point later. */ p = ++dst; count = (valueBits + integerPartWidth - 1) / integerPartWidth; while (outputDigits && count) { integerPart part; /* Put the most significant integerPartWidth bits in "part". */ if (--count == partsCount) part = 0; /* An imaginary higher zero part. */ else part = significand[count] << shift; if (count && shift) part |= significand[count - 1] >> (integerPartWidth - shift); /* Convert as much of "part" to hexdigits as we can. */ unsigned int curDigits = integerPartWidth / 4; if (curDigits > outputDigits) curDigits = outputDigits; dst += partAsHex (dst, part, curDigits, hexDigitChars); outputDigits -= curDigits; } if (roundUp) { char *q = dst; /* Note that hexDigitChars has a trailing '0'. */ do { q--; *q = hexDigitChars[hexDigitValue (*q) + 1]; } while (*q == '0'); assert(q >= p); } else { /* Add trailing zeroes. */ memset (dst, '0', outputDigits); dst += outputDigits; } /* Move the most significant digit to before the point, and if there is something after the decimal point add it. This must come after rounding above. */ p[-1] = p[0]; if (dst -1 == p) dst--; else p[0] = '.'; /* Finally output the exponent. */ *dst++ = upperCase ? 'P': 'p'; return writeSignedDecimal (dst, exponent); } // For good performance it is desirable for different APFloats // to produce different integers. uint32_t APFloat::getHashValue() const { if (category==fcZero) return sign<<8 | semantics->precision ; else if (category==fcInfinity) return sign<<9 | semantics->precision; else if (category==fcNaN) return 1<<10 | semantics->precision; else { uint32_t hash = sign<<11 | semantics->precision | exponent<<12; const integerPart* p = significandParts(); for (int i=partCount(); i>0; i--, p++) hash ^= ((uint32_t)*p) ^ (uint32_t)((*p)>>32); return hash; } } // Conversion from APFloat to/from host float/double. It may eventually be // possible to eliminate these and have everybody deal with APFloats, but that // will take a while. This approach will not easily extend to long double. // Current implementation requires integerPartWidth==64, which is correct at // the moment but could be made more general. // Denormals have exponent minExponent in APFloat, but minExponent-1 in // the actual IEEE respresentations. We compensate for that here. APInt APFloat::convertF80LongDoubleAPFloatToAPInt() const { assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended); assert(partCount()==2); uint64_t myexponent, mysignificand; if (category==fcNormal) { myexponent = exponent+16383; //bias mysignificand = significandParts()[0]; if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL)) myexponent = 0; // denormal } else if (category==fcZero) { myexponent = 0; mysignificand = 0; } else if (category==fcInfinity) { myexponent = 0x7fff; mysignificand = 0x8000000000000000ULL; } else { assert(category == fcNaN && "Unknown category"); myexponent = 0x7fff; mysignificand = significandParts()[0]; } uint64_t words[2]; words[0] = mysignificand; words[1] = ((uint64_t)(sign & 1) << 15) | (myexponent & 0x7fffLL); return APInt(80, words); } APInt APFloat::convertPPCDoubleDoubleAPFloatToAPInt() const { assert(semantics == (const llvm::fltSemantics*)&PPCDoubleDouble); assert(partCount()==2); uint64_t myexponent, mysignificand, myexponent2, mysignificand2; if (category==fcNormal) { myexponent = exponent + 1023; //bias myexponent2 = exponent2 + 1023; mysignificand = significandParts()[0]; mysignificand2 = significandParts()[1]; if (myexponent==1 && !(mysignificand & 0x10000000000000LL)) myexponent = 0; // denormal if (myexponent2==1 && !(mysignificand2 & 0x10000000000000LL)) myexponent2 = 0; // denormal } else if (category==fcZero) { myexponent = 0; mysignificand = 0; myexponent2 = 0; mysignificand2 = 0; } else if (category==fcInfinity) { myexponent = 0x7ff; myexponent2 = 0; mysignificand = 0; mysignificand2 = 0; } else { assert(category == fcNaN && "Unknown category"); myexponent = 0x7ff; mysignificand = significandParts()[0]; myexponent2 = exponent2; mysignificand2 = significandParts()[1]; } uint64_t words[2]; words[0] = ((uint64_t)(sign & 1) << 63) | ((myexponent & 0x7ff) << 52) | (mysignificand & 0xfffffffffffffLL); words[1] = ((uint64_t)(sign2 & 1) << 63) | ((myexponent2 & 0x7ff) << 52) | (mysignificand2 & 0xfffffffffffffLL); return APInt(128, words); } APInt APFloat::convertQuadrupleAPFloatToAPInt() const { assert(semantics == (const llvm::fltSemantics*)&IEEEquad); assert(partCount()==2); uint64_t myexponent, mysignificand, mysignificand2; if (category==fcNormal) { myexponent = exponent+16383; //bias mysignificand = significandParts()[0]; mysignificand2 = significandParts()[1]; if (myexponent==1 && !(mysignificand2 & 0x1000000000000LL)) myexponent = 0; // denormal } else if (category==fcZero) { myexponent = 0; mysignificand = mysignificand2 = 0; } else if (category==fcInfinity) { myexponent = 0x7fff; mysignificand = mysignificand2 = 0; } else { assert(category == fcNaN && "Unknown category!"); myexponent = 0x7fff; mysignificand = significandParts()[0]; mysignificand2 = significandParts()[1]; } uint64_t words[2]; words[0] = mysignificand; words[1] = ((uint64_t)(sign & 1) << 63) | ((myexponent & 0x7fff) << 48) | (mysignificand2 & 0xffffffffffffLL); return APInt(128, words); } APInt APFloat::convertDoubleAPFloatToAPInt() const { assert(semantics == (const llvm::fltSemantics*)&IEEEdouble); assert(partCount()==1); uint64_t myexponent, mysignificand; if (category==fcNormal) { myexponent = exponent+1023; //bias mysignificand = *significandParts(); if (myexponent==1 && !(mysignificand & 0x10000000000000LL)) myexponent = 0; // denormal } else if (category==fcZero) { myexponent = 0; mysignificand = 0; } else if (category==fcInfinity) { myexponent = 0x7ff; mysignificand = 0; } else { assert(category == fcNaN && "Unknown category!"); myexponent = 0x7ff; mysignificand = *significandParts(); } return APInt(64, ((((uint64_t)(sign & 1) << 63) | ((myexponent & 0x7ff) << 52) | (mysignificand & 0xfffffffffffffLL)))); } APInt APFloat::convertFloatAPFloatToAPInt() const { assert(semantics == (const llvm::fltSemantics*)&IEEEsingle); assert(partCount()==1); uint32_t myexponent, mysignificand; if (category==fcNormal) { myexponent = exponent+127; //bias mysignificand = (uint32_t)*significandParts(); if (myexponent == 1 && !(mysignificand & 0x800000)) myexponent = 0; // denormal } else if (category==fcZero) { myexponent = 0; mysignificand = 0; } else if (category==fcInfinity) { myexponent = 0xff; mysignificand = 0; } else { assert(category == fcNaN && "Unknown category!"); myexponent = 0xff; mysignificand = (uint32_t)*significandParts(); } return APInt(32, (((sign&1) << 31) | ((myexponent&0xff) << 23) | (mysignificand & 0x7fffff))); } APInt APFloat::convertHalfAPFloatToAPInt() const { assert(semantics == (const llvm::fltSemantics*)&IEEEhalf); assert(partCount()==1); uint32_t myexponent, mysignificand; if (category==fcNormal) { myexponent = exponent+15; //bias mysignificand = (uint32_t)*significandParts(); if (myexponent == 1 && !(mysignificand & 0x400)) myexponent = 0; // denormal } else if (category==fcZero) { myexponent = 0; mysignificand = 0; } else if (category==fcInfinity) { myexponent = 0x1f; mysignificand = 0; } else { assert(category == fcNaN && "Unknown category!"); myexponent = 0x1f; mysignificand = (uint32_t)*significandParts(); } return APInt(16, (((sign&1) << 15) | ((myexponent&0x1f) << 10) | (mysignificand & 0x3ff))); } // This function creates an APInt that is just a bit map of the floating // point constant as it would appear in memory. It is not a conversion, // and treating the result as a normal integer is unlikely to be useful. APInt APFloat::bitcastToAPInt() const { if (semantics == (const llvm::fltSemantics*)&IEEEhalf) return convertHalfAPFloatToAPInt(); if (semantics == (const llvm::fltSemantics*)&IEEEsingle) return convertFloatAPFloatToAPInt(); if (semantics == (const llvm::fltSemantics*)&IEEEdouble) return convertDoubleAPFloatToAPInt(); if (semantics == (const llvm::fltSemantics*)&IEEEquad) return convertQuadrupleAPFloatToAPInt(); if (semantics == (const llvm::fltSemantics*)&PPCDoubleDouble) return convertPPCDoubleDoubleAPFloatToAPInt(); assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended && "unknown format!"); return convertF80LongDoubleAPFloatToAPInt(); } float APFloat::convertToFloat() const { assert(semantics == (const llvm::fltSemantics*)&IEEEsingle && "Float semantics are not IEEEsingle"); APInt api = bitcastToAPInt(); return api.bitsToFloat(); } double APFloat::convertToDouble() const { assert(semantics == (const llvm::fltSemantics*)&IEEEdouble && "Float semantics are not IEEEdouble"); APInt api = bitcastToAPInt(); return api.bitsToDouble(); } /// Integer bit is explicit in this format. Intel hardware (387 and later) /// does not support these bit patterns: /// exponent = all 1's, integer bit 0, significand 0 ("pseudoinfinity") /// exponent = all 1's, integer bit 0, significand nonzero ("pseudoNaN") /// exponent = 0, integer bit 1 ("pseudodenormal") /// exponent!=0 nor all 1's, integer bit 0 ("unnormal") /// At the moment, the first two are treated as NaNs, the second two as Normal. void APFloat::initFromF80LongDoubleAPInt(const APInt &api) { assert(api.getBitWidth()==80); uint64_t i1 = api.getRawData()[0]; uint64_t i2 = api.getRawData()[1]; uint64_t myexponent = (i2 & 0x7fff); uint64_t mysignificand = i1; initialize(&APFloat::x87DoubleExtended); assert(partCount()==2); sign = static_cast<unsigned int>(i2>>15); if (myexponent==0 && mysignificand==0) { // exponent, significand meaningless category = fcZero; } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) { // exponent, significand meaningless category = fcInfinity; } else if (myexponent==0x7fff && mysignificand!=0x8000000000000000ULL) { // exponent meaningless category = fcNaN; significandParts()[0] = mysignificand; significandParts()[1] = 0; } else { category = fcNormal; exponent = myexponent - 16383; significandParts()[0] = mysignificand; significandParts()[1] = 0; if (myexponent==0) // denormal exponent = -16382; } } void APFloat::initFromPPCDoubleDoubleAPInt(const APInt &api) { assert(api.getBitWidth()==128); uint64_t i1 = api.getRawData()[0]; uint64_t i2 = api.getRawData()[1]; uint64_t myexponent = (i1 >> 52) & 0x7ff; uint64_t mysignificand = i1 & 0xfffffffffffffLL; uint64_t myexponent2 = (i2 >> 52) & 0x7ff; uint64_t mysignificand2 = i2 & 0xfffffffffffffLL; initialize(&APFloat::PPCDoubleDouble); assert(partCount()==2); sign = static_cast<unsigned int>(i1>>63); sign2 = static_cast<unsigned int>(i2>>63); if (myexponent==0 && mysignificand==0) { // exponent, significand meaningless // exponent2 and significand2 are required to be 0; we don't check category = fcZero; } else if (myexponent==0x7ff && mysignificand==0) { // exponent, significand meaningless // exponent2 and significand2 are required to be 0; we don't check category = fcInfinity; } else if (myexponent==0x7ff && mysignificand!=0) { // exponent meaningless. So is the whole second word, but keep it // for determinism. category = fcNaN; exponent2 = myexponent2; significandParts()[0] = mysignificand; significandParts()[1] = mysignificand2; } else { category = fcNormal; // Note there is no category2; the second word is treated as if it is // fcNormal, although it might be something else considered by itself. exponent = myexponent - 1023; exponent2 = myexponent2 - 1023; significandParts()[0] = mysignificand; significandParts()[1] = mysignificand2; if (myexponent==0) // denormal exponent = -1022; else significandParts()[0] |= 0x10000000000000LL; // integer bit if (myexponent2==0) exponent2 = -1022; else significandParts()[1] |= 0x10000000000000LL; // integer bit } } void APFloat::initFromQuadrupleAPInt(const APInt &api) { assert(api.getBitWidth()==128); uint64_t i1 = api.getRawData()[0]; uint64_t i2 = api.getRawData()[1]; uint64_t myexponent = (i2 >> 48) & 0x7fff; uint64_t mysignificand = i1; uint64_t mysignificand2 = i2 & 0xffffffffffffLL; initialize(&APFloat::IEEEquad); assert(partCount()==2); sign = static_cast<unsigned int>(i2>>63); if (myexponent==0 && (mysignificand==0 && mysignificand2==0)) { // exponent, significand meaningless category = fcZero; } else if (myexponent==0x7fff && (mysignificand==0 && mysignificand2==0)) { // exponent, significand meaningless category = fcInfinity; } else if (myexponent==0x7fff && (mysignificand!=0 || mysignificand2 !=0)) { // exponent meaningless category = fcNaN; significandParts()[0] = mysignificand; significandParts()[1] = mysignificand2; } else { category = fcNormal; exponent = myexponent - 16383; significandParts()[0] = mysignificand; significandParts()[1] = mysignificand2; if (myexponent==0) // denormal exponent = -16382; else significandParts()[1] |= 0x1000000000000LL; // integer bit } } void APFloat::initFromDoubleAPInt(const APInt &api) { assert(api.getBitWidth()==64); uint64_t i = *api.getRawData(); uint64_t myexponent = (i >> 52) & 0x7ff; uint64_t mysignificand = i & 0xfffffffffffffLL; initialize(&APFloat::IEEEdouble); assert(partCount()==1); sign = static_cast<unsigned int>(i>>63); if (myexponent==0 && mysignificand==0) { // exponent, significand meaningless category = fcZero; } else if (myexponent==0x7ff && mysignificand==0) { // exponent, significand meaningless category = fcInfinity; } else if (myexponent==0x7ff && mysignificand!=0) { // exponent meaningless category = fcNaN; *significandParts() = mysignificand; } else { category = fcNormal; exponent = myexponent - 1023; *significandParts() = mysignificand; if (myexponent==0) // denormal exponent = -1022; else *significandParts() |= 0x10000000000000LL; // integer bit } } void APFloat::initFromFloatAPInt(const APInt & api) { assert(api.getBitWidth()==32); uint32_t i = (uint32_t)*api.getRawData(); uint32_t myexponent = (i >> 23) & 0xff; uint32_t mysignificand = i & 0x7fffff; initialize(&APFloat::IEEEsingle); assert(partCount()==1); sign = i >> 31; if (myexponent==0 && mysignificand==0) { // exponent, significand meaningless category = fcZero; } else if (myexponent==0xff && mysignificand==0) { // exponent, significand meaningless category = fcInfinity; } else if (myexponent==0xff && mysignificand!=0) { // sign, exponent, significand meaningless category = fcNaN; *significandParts() = mysignificand; } else { category = fcNormal; exponent = myexponent - 127; //bias *significandParts() = mysignificand; if (myexponent==0) // denormal exponent = -126; else *significandParts() |= 0x800000; // integer bit } } void APFloat::initFromHalfAPInt(const APInt & api) { assert(api.getBitWidth()==16); uint32_t i = (uint32_t)*api.getRawData(); uint32_t myexponent = (i >> 10) & 0x1f; uint32_t mysignificand = i & 0x3ff; initialize(&APFloat::IEEEhalf); assert(partCount()==1); sign = i >> 15; if (myexponent==0 && mysignificand==0) { // exponent, significand meaningless category = fcZero; } else if (myexponent==0x1f && mysignificand==0) { // exponent, significand meaningless category = fcInfinity; } else if (myexponent==0x1f && mysignificand!=0) { // sign, exponent, significand meaningless category = fcNaN; *significandParts() = mysignificand; } else { category = fcNormal; exponent = myexponent - 15; //bias *significandParts() = mysignificand; if (myexponent==0) // denormal exponent = -14; else *significandParts() |= 0x400; // integer bit } } /// Treat api as containing the bits of a floating point number. Currently /// we infer the floating point type from the size of the APInt. The /// isIEEE argument distinguishes between PPC128 and IEEE128 (not meaningful /// when the size is anything else). void APFloat::initFromAPInt(const APInt& api, bool isIEEE) { if (api.getBitWidth() == 16) return initFromHalfAPInt(api); else if (api.getBitWidth() == 32) return initFromFloatAPInt(api); else if (api.getBitWidth()==64) return initFromDoubleAPInt(api); else if (api.getBitWidth()==80) return initFromF80LongDoubleAPInt(api); else if (api.getBitWidth()==128) return (isIEEE ? initFromQuadrupleAPInt(api) : initFromPPCDoubleDoubleAPInt(api)); else abort(); } APFloat APFloat::getAllOnesValue(unsigned BitWidth, bool isIEEE) { return APFloat(APInt::getAllOnesValue(BitWidth), isIEEE); } APFloat APFloat::getLargest(const fltSemantics &Sem, bool Negative) { APFloat Val(Sem, fcNormal, Negative); // We want (in interchange format): // sign = {Negative} // exponent = 1..10 // significand = 1..1 Val.exponent = Sem.maxExponent; // unbiased // 1-initialize all bits.... Val.zeroSignificand(); integerPart *significand = Val.significandParts(); unsigned N = partCountForBits(Sem.precision); for (unsigned i = 0; i != N; ++i) significand[i] = ~((integerPart) 0); // ...and then clear the top bits for internal consistency. significand[N-1] &= (((integerPart) 1) << ((Sem.precision % integerPartWidth) - 1)) - 1; return Val; } APFloat APFloat::getSmallest(const fltSemantics &Sem, bool Negative) { APFloat Val(Sem, fcNormal, Negative); // We want (in interchange format): // sign = {Negative} // exponent = 0..0 // significand = 0..01 Val.exponent = Sem.minExponent; // unbiased Val.zeroSignificand(); Val.significandParts()[0] = 1; return Val; } APFloat APFloat::getSmallestNormalized(const fltSemantics &Sem, bool Negative) { APFloat Val(Sem, fcNormal, Negative); // We want (in interchange format): // sign = {Negative} // exponent = 0..0 // significand = 10..0 Val.exponent = Sem.minExponent; Val.zeroSignificand(); Val.significandParts()[partCountForBits(Sem.precision)-1] |= (((integerPart) 1) << ((Sem.precision % integerPartWidth) - 1)); return Val; } APFloat::APFloat(const APInt& api, bool isIEEE) : exponent2(0), sign2(0) { initFromAPInt(api, isIEEE); } APFloat::APFloat(float f) : exponent2(0), sign2(0) { initFromAPInt(APInt::floatToBits(f)); } APFloat::APFloat(double d) : exponent2(0), sign2(0) { initFromAPInt(APInt::doubleToBits(d)); } namespace { static void append(SmallVectorImpl<char> &Buffer, unsigned N, const char *Str) { unsigned Start = Buffer.size(); Buffer.set_size(Start + N); memcpy(&Buffer[Start], Str, N); } template <unsigned N> void append(SmallVectorImpl<char> &Buffer, const char (&Str)[N]) { append(Buffer, N, Str); } /// Removes data from the given significand until it is no more /// precise than is required for the desired precision. void AdjustToPrecision(APInt &significand, int &exp, unsigned FormatPrecision) { unsigned bits = significand.getActiveBits(); // 196/59 is a very slight overestimate of lg_2(10). unsigned bitsRequired = (FormatPrecision * 196 + 58) / 59; if (bits <= bitsRequired) return; unsigned tensRemovable = (bits - bitsRequired) * 59 / 196; if (!tensRemovable) return; exp += tensRemovable; APInt divisor(significand.getBitWidth(), 1); APInt powten(significand.getBitWidth(), 10); while (true) { if (tensRemovable & 1) divisor *= powten; tensRemovable >>= 1; if (!tensRemovable) break; powten *= powten; } significand = significand.udiv(divisor); // Truncate the significand down to its active bit count, but // don't try to drop below 32. unsigned newPrecision = std::max(32U, significand.getActiveBits()); significand = significand.trunc(newPrecision); } void AdjustToPrecision(SmallVectorImpl<char> &buffer, int &exp, unsigned FormatPrecision) { unsigned N = buffer.size(); if (N <= FormatPrecision) return; // The most significant figures are the last ones in the buffer. unsigned FirstSignificant = N - FormatPrecision; // Round. // FIXME: this probably shouldn't use 'round half up'. // Rounding down is just a truncation, except we also want to drop // trailing zeros from the new result. if (buffer[FirstSignificant - 1] < '5') { while (buffer[FirstSignificant] == '0') FirstSignificant++; exp += FirstSignificant; buffer.erase(&buffer[0], &buffer[FirstSignificant]); return; } // Rounding up requires a decimal add-with-carry. If we continue // the carry, the newly-introduced zeros will just be truncated. for (unsigned I = FirstSignificant; I != N; ++I) { if (buffer[I] == '9') { FirstSignificant++; } else { buffer[I]++; break; } } // If we carried through, we have exactly one digit of precision. if (FirstSignificant == N) { exp += FirstSignificant; buffer.clear(); buffer.push_back('1'); return; } exp += FirstSignificant; buffer.erase(&buffer[0], &buffer[FirstSignificant]); } } void APFloat::toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision, unsigned FormatMaxPadding) const { switch (category) { case fcInfinity: if (isNegative()) return append(Str, "-Inf"); else return append(Str, "+Inf"); case fcNaN: return append(Str, "NaN"); case fcZero: if (isNegative()) Str.push_back('-'); if (!FormatMaxPadding) append(Str, "0.0E+0"); else Str.push_back('0'); return; case fcNormal: break; } if (isNegative()) Str.push_back('-'); // Decompose the number into an APInt and an exponent. int exp = exponent - ((int) semantics->precision - 1); APInt significand(semantics->precision, makeArrayRef(significandParts(), partCountForBits(semantics->precision))); // Set FormatPrecision if zero. We want to do this before we // truncate trailing zeros, as those are part of the precision. if (!FormatPrecision) { // It's an interesting question whether to use the nominal // precision or the active precision here for denormals. // FormatPrecision = ceil(significandBits / lg_2(10)) FormatPrecision = (semantics->precision * 59 + 195) / 196; } // Ignore trailing binary zeros. int trailingZeros = significand.countTrailingZeros(); exp += trailingZeros; significand = significand.lshr(trailingZeros); // Change the exponent from 2^e to 10^e. if (exp == 0) { // Nothing to do. } else if (exp > 0) { // Just shift left. significand = significand.zext(semantics->precision + exp); significand <<= exp; exp = 0; } else { /* exp < 0 */ int texp = -exp; // We transform this using the identity: // (N)(2^-e) == (N)(5^e)(10^-e) // This means we have to multiply N (the significand) by 5^e. // To avoid overflow, we have to operate on numbers large // enough to store N * 5^e: // log2(N * 5^e) == log2(N) + e * log2(5) // <= semantics->precision + e * 137 / 59 // (log_2(5) ~ 2.321928 < 2.322034 ~ 137/59) unsigned precision = semantics->precision + 137 * texp / 59; // Multiply significand by 5^e. // N * 5^0101 == N * 5^(1*1) * 5^(0*2) * 5^(1*4) * 5^(0*8) significand = significand.zext(precision); APInt five_to_the_i(precision, 5); while (true) { if (texp & 1) significand *= five_to_the_i; texp >>= 1; if (!texp) break; five_to_the_i *= five_to_the_i; } } AdjustToPrecision(significand, exp, FormatPrecision); llvm::SmallVector<char, 256> buffer; // Fill the buffer. unsigned precision = significand.getBitWidth(); APInt ten(precision, 10); APInt digit(precision, 0); bool inTrail = true; while (significand != 0) { // digit <- significand % 10 // significand <- significand / 10 APInt::udivrem(significand, ten, significand, digit); unsigned d = digit.getZExtValue(); // Drop trailing zeros. if (inTrail && !d) exp++; else { buffer.push_back((char) ('0' + d)); inTrail = false; } } assert(!buffer.empty() && "no characters in buffer!"); // Drop down to FormatPrecision. // TODO: don't do more precise calculations above than are required. AdjustToPrecision(buffer, exp, FormatPrecision); unsigned NDigits = buffer.size(); // Check whether we should use scientific notation. bool FormatScientific; if (!FormatMaxPadding) FormatScientific = true; else { if (exp >= 0) { // 765e3 --> 765000 // ^^^ // But we shouldn't make the number look more precise than it is. FormatScientific = ((unsigned) exp > FormatMaxPadding || NDigits + (unsigned) exp > FormatPrecision); } else { // Power of the most significant digit. int MSD = exp + (int) (NDigits - 1); if (MSD >= 0) { // 765e-2 == 7.65 FormatScientific = false; } else { // 765e-5 == 0.00765 // ^ ^^ FormatScientific = ((unsigned) -MSD) > FormatMaxPadding; } } } // Scientific formatting is pretty straightforward. if (FormatScientific) { exp += (NDigits - 1); Str.push_back(buffer[NDigits-1]); Str.push_back('.'); if (NDigits == 1) Str.push_back('0'); else for (unsigned I = 1; I != NDigits; ++I) Str.push_back(buffer[NDigits-1-I]); Str.push_back('E'); Str.push_back(exp >= 0 ? '+' : '-'); if (exp < 0) exp = -exp; SmallVector<char, 6> expbuf; do { expbuf.push_back((char) ('0' + (exp % 10))); exp /= 10; } while (exp); for (unsigned I = 0, E = expbuf.size(); I != E; ++I) Str.push_back(expbuf[E-1-I]); return; } // Non-scientific, positive exponents. if (exp >= 0) { for (unsigned I = 0; I != NDigits; ++I) Str.push_back(buffer[NDigits-1-I]); for (unsigned I = 0; I != (unsigned) exp; ++I) Str.push_back('0'); return; } // Non-scientific, negative exponents. // The number of digits to the left of the decimal point. int NWholeDigits = exp + (int) NDigits; unsigned I = 0; if (NWholeDigits > 0) { for (; I != (unsigned) NWholeDigits; ++I) Str.push_back(buffer[NDigits-I-1]); Str.push_back('.'); } else { unsigned NZeros = 1 + (unsigned) -NWholeDigits; Str.push_back('0'); Str.push_back('.'); for (unsigned Z = 1; Z != NZeros; ++Z) Str.push_back('0'); } for (; I != NDigits; ++I) Str.push_back(buffer[NDigits-I-1]); } bool APFloat::getExactInverse(APFloat *inv) const { // We can only guarantee the existence of an exact inverse for IEEE floats. if (semantics != &IEEEhalf && semantics != &IEEEsingle && semantics != &IEEEdouble && semantics != &IEEEquad) return false; // Special floats and denormals have no exact inverse. if (category != fcNormal) return false; // Check that the number is a power of two by making sure that only the // integer bit is set in the significand. if (significandLSB() != semantics->precision - 1) return false; // Get the inverse. APFloat reciprocal(*semantics, 1ULL); if (reciprocal.divide(*this, rmNearestTiesToEven) != opOK) return false; // Avoid multiplication with a denormal, it is not safe on all platforms and // may be slower than a normal division. if (reciprocal.significandMSB() + 1 < reciprocal.semantics->precision) return false; assert(reciprocal.category == fcNormal && reciprocal.significandLSB() == reciprocal.semantics->precision - 1); if (inv) *inv = reciprocal; return true; }
0
rapidsai_public_repos/code-share/maxflow/galois/src
rapidsai_public_repos/code-share/maxflow/galois/src/llvm/SmallVector.cpp
//===- llvm/ADT/SmallVector.cpp - 'Normally small' vectors ----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the SmallVector class. // //===----------------------------------------------------------------------===// #include "llvm/ADT/SmallVector.h" using namespace llvm; /// grow_pod - This is an implementation of the grow() method which only works /// on POD-like datatypes and is out of line to reduce code duplication. void SmallVectorBase::grow_pod(size_t MinSizeInBytes, size_t TSize) { size_t CurSizeBytes = size_in_bytes(); size_t NewCapacityInBytes = 2 * capacity_in_bytes() + TSize; // Always grow. if (NewCapacityInBytes < MinSizeInBytes) NewCapacityInBytes = MinSizeInBytes; void *NewElts; if (this->isSmall()) { NewElts = malloc(NewCapacityInBytes); // Copy the elements over. No need to run dtors on PODs. memcpy(NewElts, this->BeginX, CurSizeBytes); } else { // If this wasn't grown from the inline copy, grow the allocated space. NewElts = realloc(this->BeginX, NewCapacityInBytes); } this->EndX = (char*)NewElts+CurSizeBytes; this->BeginX = NewElts; this->CapacityX = (char*)this->BeginX + NewCapacityInBytes; }
0
rapidsai_public_repos/code-share/maxflow/galois/src
rapidsai_public_repos/code-share/maxflow/galois/src/llvm/CommandLine.cpp
//===-- CommandLine.cpp - Command line parser implementation --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This class implements a command line argument processor that is useful when // creating a tool. It provides a simple, minimalistic interface that is easily // extensible and supports nonlocal (library) command line options. // // Note that rather than trying to figure out what this code does, you could try // reading the library documentation located in docs/CommandLine.html // //===----------------------------------------------------------------------===// #include "llvm/Support/CommandLine.h" //#include "llvm/Support/ErrorHandling.h" //#include "llvm/Support/MemoryBuffer.h" //#include "llvm/Support/system_error.h" //#include "llvm/Support/Host.h" //#include "llvm/ADT/OwningPtr.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/Twine.h" #include <iostream> #include <sstream> #include <cerrno> #include <cstdlib> using namespace llvm; using namespace cl; //===----------------------------------------------------------------------===// // Template instantiations and anchors. // namespace llvm { namespace cl { TEMPLATE_INSTANTIATION(class basic_parser<bool>); TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>); TEMPLATE_INSTANTIATION(class basic_parser<int>); TEMPLATE_INSTANTIATION(class basic_parser<unsigned>); TEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>); TEMPLATE_INSTANTIATION(class basic_parser<double>); TEMPLATE_INSTANTIATION(class basic_parser<float>); TEMPLATE_INSTANTIATION(class basic_parser<std::string>); TEMPLATE_INSTANTIATION(class basic_parser<char>); TEMPLATE_INSTANTIATION(class opt<unsigned>); TEMPLATE_INSTANTIATION(class opt<int>); TEMPLATE_INSTANTIATION(class opt<std::string>); TEMPLATE_INSTANTIATION(class opt<char>); TEMPLATE_INSTANTIATION(class opt<bool>); } } // end namespace llvm::cl void Option::anchor() {} void basic_parser_impl::anchor() {} void parser<bool>::anchor() {} void parser<boolOrDefault>::anchor() {} void parser<int>::anchor() {} void parser<unsigned>::anchor() {} void parser<unsigned long long>::anchor() {} void parser<double>::anchor() {} void parser<float>::anchor() {} void parser<std::string>::anchor() {} void parser<char>::anchor() {} //===----------------------------------------------------------------------===// // This collects additional help to be printed. static std::vector<const char*> MoreHelp; extrahelp::extrahelp(const char *Help) : morehelp(Help) { MoreHelp.push_back(Help); } static bool OptionListChanged = false; // MarkOptionsChanged - Internal helper function. void cl::MarkOptionsChanged() { OptionListChanged = true; } /// RegisteredOptionList - This is the list of the command line options that /// have statically constructed themselves. static Option *RegisteredOptionList = 0; void Option::addArgument() { assert(NextRegistered == 0 && "argument multiply registered!"); NextRegistered = RegisteredOptionList; RegisteredOptionList = this; MarkOptionsChanged(); } //===----------------------------------------------------------------------===// // Basic, shared command line option processing machinery. // std::string getIndent(int n) { std::string indent; for (int x = 0; x < n; ++x) indent.push_back(' '); return indent; } /// GetOptionInfo - Scan the list of registered options, turning them into data /// structures that are easier to handle. static void GetOptionInfo(SmallVectorImpl<Option*> &PositionalOpts, SmallVectorImpl<Option*> &SinkOpts, StringMap<Option*> &OptionsMap) { SmallVector<const char*, 16> OptionNames; Option *CAOpt = 0; // The ConsumeAfter option if it exists. for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) { // If this option wants to handle multiple option names, get the full set. // This handles enum options like "-O1 -O2" etc. O->getExtraOptionNames(OptionNames); if (O->ArgStr[0]) OptionNames.push_back(O->ArgStr); // Handle named options. for (size_t i = 0, e = OptionNames.size(); i != e; ++i) { // Add argument to the argument map! if (OptionsMap.GetOrCreateValue(OptionNames[i], O).second != O) { std::cerr << "CommandLine Error: Argument '" << OptionNames[i] << "' defined more than once!\n"; } } OptionNames.clear(); // Remember information about positional options. if (O->getFormattingFlag() == cl::Positional) PositionalOpts.push_back(O); else if (O->getMiscFlags() & cl::Sink) // Remember sink options SinkOpts.push_back(O); else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) { if (CAOpt) O->error("Cannot specify more than one option with cl::ConsumeAfter!"); CAOpt = O; } } if (CAOpt) PositionalOpts.push_back(CAOpt); // Make sure that they are in order of registration not backwards. std::reverse(PositionalOpts.begin(), PositionalOpts.end()); } /// LookupOption - Lookup the option specified by the specified option on the /// command line. If there is a value specified (after an equal sign) return /// that as well. This assumes that leading dashes have already been stripped. static Option *LookupOption(StringRef &Arg, StringRef &Value, const StringMap<Option*> &OptionsMap) { // Reject all dashes. if (Arg.empty()) return 0; size_t EqualPos = Arg.find('='); // If we have an equals sign, remember the value. if (EqualPos == StringRef::npos) { // Look up the option. StringMap<Option*>::const_iterator I = OptionsMap.find(Arg); return I != OptionsMap.end() ? I->second : 0; } // If the argument before the = is a valid option name, we match. If not, // return Arg unmolested. StringMap<Option*>::const_iterator I = OptionsMap.find(Arg.substr(0, EqualPos)); if (I == OptionsMap.end()) return 0; Value = Arg.substr(EqualPos+1); Arg = Arg.substr(0, EqualPos); return I->second; } /// LookupNearestOption - Lookup the closest match to the option specified by /// the specified option on the command line. If there is a value specified /// (after an equal sign) return that as well. This assumes that leading dashes /// have already been stripped. static Option *LookupNearestOption(StringRef Arg, const StringMap<Option*> &OptionsMap, std::string &NearestString) { // Reject all dashes. if (Arg.empty()) return 0; // Split on any equal sign. std::pair<StringRef, StringRef> SplitArg = Arg.split('='); StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present. StringRef &RHS = SplitArg.second; // Find the closest match. Option *Best = 0; unsigned BestDistance = 0; for (StringMap<Option*>::const_iterator it = OptionsMap.begin(), ie = OptionsMap.end(); it != ie; ++it) { Option *O = it->second; SmallVector<const char*, 16> OptionNames; O->getExtraOptionNames(OptionNames); if (O->ArgStr[0]) OptionNames.push_back(O->ArgStr); bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed; StringRef Flag = PermitValue ? LHS : Arg; for (size_t i = 0, e = OptionNames.size(); i != e; ++i) { StringRef Name = OptionNames[i]; unsigned Distance = StringRef(Name).edit_distance( Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance); if (!Best || Distance < BestDistance) { Best = O; BestDistance = Distance; if (RHS.empty() || !PermitValue) NearestString = OptionNames[i]; else NearestString = std::string(OptionNames[i]) + "=" + RHS.str(); } } } return Best; } /// CommaSeparateAndAddOccurence - A wrapper around Handler->addOccurence() that /// does special handling of cl::CommaSeparated options. static bool CommaSeparateAndAddOccurence(Option *Handler, unsigned pos, StringRef ArgName, StringRef Value, bool MultiArg = false) { // Check to see if this option accepts a comma separated list of values. If // it does, we have to split up the value into multiple values. if (Handler->getMiscFlags() & CommaSeparated) { StringRef Val(Value); StringRef::size_type Pos = Val.find(','); while (Pos != StringRef::npos) { // Process the portion before the comma. if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg)) return true; // Erase the portion before the comma, AND the comma. Val = Val.substr(Pos+1); Value.substr(Pos+1); // Increment the original value pointer as well. // Check for another comma. Pos = Val.find(','); } Value = Val; } if (Handler->addOccurrence(pos, ArgName, Value, MultiArg)) return true; return false; } /// ProvideOption - For Value, this differentiates between an empty value ("") /// and a null value (StringRef()). The later is accepted for arguments that /// don't allow a value (-foo) the former is rejected (-foo=). static inline bool ProvideOption(Option *Handler, StringRef ArgName, StringRef Value, int argc, char **argv, int &i) { // Is this a multi-argument option? unsigned NumAdditionalVals = Handler->getNumAdditionalVals(); // Enforce value requirements switch (Handler->getValueExpectedFlag()) { case ValueRequired: if (Value.data() == 0) { // No value specified? if (i+1 >= argc) return Handler->error("requires a value!"); // Steal the next argument, like for '-o filename' Value = argv[++i]; } break; case ValueDisallowed: if (NumAdditionalVals > 0) return Handler->error("multi-valued option specified" " with ValueDisallowed modifier!"); if (Value.data()) return Handler->error("does not allow a value! '" + Twine(Value) + "' specified."); break; case ValueOptional: break; default: std::cerr << "Bad ValueMask flag! CommandLine usage error:" << Handler->getValueExpectedFlag() << "\n"; abort(); } // If this isn't a multi-arg option, just run the handler. if (NumAdditionalVals == 0) return CommaSeparateAndAddOccurence(Handler, i, ArgName, Value); // If it is, run the handle several times. bool MultiArg = false; if (Value.data()) { if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg)) return true; --NumAdditionalVals; MultiArg = true; } while (NumAdditionalVals > 0) { if (i+1 >= argc) return Handler->error("not enough values!"); Value = argv[++i]; if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg)) return true; MultiArg = true; --NumAdditionalVals; } return false; } static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) { int Dummy = i; return ProvideOption(Handler, Handler->ArgStr, Arg, 0, 0, Dummy); } // Option predicates... static inline bool isGrouping(const Option *O) { return O->getFormattingFlag() == cl::Grouping; } static inline bool isPrefixedOrGrouping(const Option *O) { return isGrouping(O) || O->getFormattingFlag() == cl::Prefix; } // getOptionPred - Check to see if there are any options that satisfy the // specified predicate with names that are the prefixes in Name. This is // checked by progressively stripping characters off of the name, checking to // see if there options that satisfy the predicate. If we find one, return it, // otherwise return null. // static Option *getOptionPred(StringRef Name, size_t &Length, bool (*Pred)(const Option*), const StringMap<Option*> &OptionsMap) { StringMap<Option*>::const_iterator OMI = OptionsMap.find(Name); // Loop while we haven't found an option and Name still has at least two // characters in it (so that the next iteration will not be the empty // string. while (OMI == OptionsMap.end() && Name.size() > 1) { Name = Name.substr(0, Name.size()-1); // Chop off the last character. OMI = OptionsMap.find(Name); } if (OMI != OptionsMap.end() && Pred(OMI->second)) { Length = Name.size(); return OMI->second; // Found one! } return 0; // No option found! } /// HandlePrefixedOrGroupedOption - The specified argument string (which started /// with at least one '-') does not fully match an available option. Check to /// see if this is a prefix or grouped option. If so, split arg into output an /// Arg/Value pair and return the Option to parse it with. static Option *HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value, bool &ErrorParsing, const StringMap<Option*> &OptionsMap) { if (Arg.size() == 1) return 0; // Do the lookup! size_t Length = 0; Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap); if (PGOpt == 0) return 0; // If the option is a prefixed option, then the value is simply the // rest of the name... so fall through to later processing, by // setting up the argument name flags and value fields. if (PGOpt->getFormattingFlag() == cl::Prefix) { Value = Arg.substr(Length); Arg = Arg.substr(0, Length); assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt); return PGOpt; } // This must be a grouped option... handle them now. Grouping options can't // have values. assert(isGrouping(PGOpt) && "Broken getOptionPred!"); do { // Move current arg name out of Arg into OneArgName. StringRef OneArgName = Arg.substr(0, Length); Arg = Arg.substr(Length); // Because ValueRequired is an invalid flag for grouped arguments, // we don't need to pass argc/argv in. assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired && "Option can not be cl::Grouping AND cl::ValueRequired!"); int Dummy = 0; ErrorParsing |= ProvideOption(PGOpt, OneArgName, StringRef(), 0, 0, Dummy); // Get the next grouping option. PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap); } while (PGOpt && Length != Arg.size()); // Return the last option with Arg cut down to just the last one. return PGOpt; } static bool RequiresValue(const Option *O) { return O->getNumOccurrencesFlag() == cl::Required || O->getNumOccurrencesFlag() == cl::OneOrMore; } static bool EatsUnboundedNumberOfValues(const Option *O) { return O->getNumOccurrencesFlag() == cl::ZeroOrMore || O->getNumOccurrencesFlag() == cl::OneOrMore; } /// ParseCStringVector - Break INPUT up wherever one or more /// whitespace characters are found, and store the resulting tokens in /// OUTPUT. The tokens stored in OUTPUT are dynamically allocated /// using strdup(), so it is the caller's responsibility to free() /// them later. /// static void ParseCStringVector(std::vector<char *> &OutputVector, const char *Input) { // Characters which will be treated as token separators: StringRef Delims = " \v\f\t\r\n"; StringRef WorkStr(Input); while (!WorkStr.empty()) { // If the first character is a delimiter, strip them off. if (Delims.find(WorkStr[0]) != StringRef::npos) { size_t Pos = WorkStr.find_first_not_of(Delims); if (Pos == StringRef::npos) Pos = WorkStr.size(); WorkStr = WorkStr.substr(Pos); continue; } // Find position of first delimiter. size_t Pos = WorkStr.find_first_of(Delims); if (Pos == StringRef::npos) Pos = WorkStr.size(); // Everything from 0 to Pos is the next word to copy. char *NewStr = (char*)malloc(Pos+1); memcpy(NewStr, WorkStr.data(), Pos); NewStr[Pos] = 0; OutputVector.push_back(NewStr); WorkStr = WorkStr.substr(Pos); } } /// ParseEnvironmentOptions - An alternative entry point to the /// CommandLine library, which allows you to read the program's name /// from the caller (as PROGNAME) and its command-line arguments from /// an environment variable (whose name is given in ENVVAR). /// void cl::ParseEnvironmentOptions(const char *progName, const char *envVar, const char *Overview) { // Check args. assert(progName && "Program name not specified"); assert(envVar && "Environment variable name missing"); // Get the environment variable they want us to parse options out of. const char *envValue = getenv(envVar); if (!envValue) return; // Get program's "name", which we wouldn't know without the caller // telling us. std::vector<char*> newArgv; newArgv.push_back(strdup(progName)); // Parse the value of the environment variable into a "command line" // and hand it off to ParseCommandLineOptions(). ParseCStringVector(newArgv, envValue); int newArgc = static_cast<int>(newArgv.size()); ParseCommandLineOptions(newArgc, &newArgv[0], Overview); // Free all the strdup()ed strings. for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end(); i != e; ++i) free(*i); } void cl::ParseCommandLineOptions(int argc, char **argv, const char *Overview) { // Process all registered options. SmallVector<Option*, 4> PositionalOpts; SmallVector<Option*, 4> SinkOpts; StringMap<Option*> Opts; GetOptionInfo(PositionalOpts, SinkOpts, Opts); assert((!Opts.empty() || !PositionalOpts.empty()) && "No options specified!"); bool ErrorParsing = false; // Check out the positional arguments to collect information about them. unsigned NumPositionalRequired = 0; // Determine whether or not there are an unlimited number of positionals bool HasUnlimitedPositionals = false; Option *ConsumeAfterOpt = 0; if (!PositionalOpts.empty()) { if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) { assert(PositionalOpts.size() > 1 && "Cannot specify cl::ConsumeAfter without a positional argument!"); ConsumeAfterOpt = PositionalOpts[0]; } // Calculate how many positional values are _required_. bool UnboundedFound = false; for (size_t i = ConsumeAfterOpt != 0, e = PositionalOpts.size(); i != e; ++i) { Option *Opt = PositionalOpts[i]; if (RequiresValue(Opt)) ++NumPositionalRequired; else if (ConsumeAfterOpt) { // ConsumeAfter cannot be combined with "optional" positional options // unless there is only one positional argument... if (PositionalOpts.size() > 2) ErrorParsing |= Opt->error("error - this positional option will never be matched, " "because it does not Require a value, and a " "cl::ConsumeAfter option is active!"); } else if (UnboundedFound && !Opt->ArgStr[0]) { // This option does not "require" a value... Make sure this option is // not specified after an option that eats all extra arguments, or this // one will never get any! // ErrorParsing |= Opt->error("error - option can never match, because " "another positional argument will match an " "unbounded number of values, and this option" " does not require a value!"); } UnboundedFound |= EatsUnboundedNumberOfValues(Opt); } HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt; } // PositionalVals - A vector of "positional" arguments we accumulate into // the process at the end. // SmallVector<std::pair<StringRef,unsigned>, 4> PositionalVals; // If the program has named positional arguments, and the name has been run // across, keep track of which positional argument was named. Otherwise put // the positional args into the PositionalVals list... Option *ActivePositionalArg = 0; // Loop over all of the arguments... processing them. bool DashDashFound = false; // Have we read '--'? for (int i = 1; i < argc; ++i) { Option *Handler = 0; Option *NearestHandler = 0; std::string NearestHandlerString; StringRef Value; StringRef ArgName = ""; // If the option list changed, this means that some command line // option has just been registered or deregistered. This can occur in // response to things like -load, etc. If this happens, rescan the options. if (OptionListChanged) { PositionalOpts.clear(); SinkOpts.clear(); Opts.clear(); GetOptionInfo(PositionalOpts, SinkOpts, Opts); OptionListChanged = false; } // Check to see if this is a positional argument. This argument is // considered to be positional if it doesn't start with '-', if it is "-" // itself, or if we have seen "--" already. // if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) { // Positional argument! if (ActivePositionalArg) { ProvidePositionalOption(ActivePositionalArg, argv[i], i); continue; // We are done! } if (!PositionalOpts.empty()) { PositionalVals.push_back(std::make_pair(argv[i],i)); // All of the positional arguments have been fulfulled, give the rest to // the consume after option... if it's specified... // if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt != 0) { for (++i; i < argc; ++i) PositionalVals.push_back(std::make_pair(argv[i],i)); break; // Handle outside of the argument processing loop... } // Delay processing positional arguments until the end... continue; } } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 && !DashDashFound) { DashDashFound = true; // This is the mythical "--"? continue; // Don't try to process it as an argument itself. } else if (ActivePositionalArg && (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) { // If there is a positional argument eating options, check to see if this // option is another positional argument. If so, treat it as an argument, // otherwise feed it to the eating positional. ArgName = argv[i]+1; // Eat leading dashes. while (!ArgName.empty() && ArgName[0] == '-') ArgName = ArgName.substr(1); Handler = LookupOption(ArgName, Value, Opts); if (!Handler || Handler->getFormattingFlag() != cl::Positional) { ProvidePositionalOption(ActivePositionalArg, argv[i], i); continue; // We are done! } } else { // We start with a '-', must be an argument. ArgName = argv[i]+1; // Eat leading dashes. while (!ArgName.empty() && ArgName[0] == '-') ArgName = ArgName.substr(1); Handler = LookupOption(ArgName, Value, Opts); // Check to see if this "option" is really a prefixed or grouped argument. if (Handler == 0) Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing, Opts); // Otherwise, look for the closest available option to report to the user // in the upcoming error. if (Handler == 0 && SinkOpts.empty()) NearestHandler = LookupNearestOption(ArgName, Opts, NearestHandlerString); } if (Handler == 0) { if (SinkOpts.empty()) { std::cerr << "Unknown command line argument '" << argv[i] << "'. Try: '" << argv[0] << " -help'\n"; if (NearestHandler) { // If we know a near match, report it as well. std::cerr << "Did you mean '-" << NearestHandlerString << "'?\n"; } ErrorParsing = true; } else { for (SmallVectorImpl<Option*>::iterator I = SinkOpts.begin(), E = SinkOpts.end(); I != E ; ++I) (*I)->addOccurrence(i, "", argv[i]); } continue; } // If this is a named positional argument, just remember that it is the // active one... if (Handler->getFormattingFlag() == cl::Positional) ActivePositionalArg = Handler; else ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i); } // Check and handle positional arguments now... if (NumPositionalRequired > PositionalVals.size()) { std::cerr << "Not enough positional command line arguments specified!\n" << "Must specify at least " << NumPositionalRequired << " positional arguments: See: " << argv[0] << " -help\n"; ErrorParsing = true; } else if (!HasUnlimitedPositionals && PositionalVals.size() > PositionalOpts.size()) { std::cerr << "Too many positional arguments specified!\n" << "Can specify at most " << PositionalOpts.size() << " positional arguments: See: " << argv[0] << " -help\n"; ErrorParsing = true; } else if (ConsumeAfterOpt == 0) { // Positional args have already been handled if ConsumeAfter is specified. unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size()); for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) { if (RequiresValue(PositionalOpts[i])) { ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first, PositionalVals[ValNo].second); ValNo++; --NumPositionalRequired; // We fulfilled our duty... } // If we _can_ give this option more arguments, do so now, as long as we // do not give it values that others need. 'Done' controls whether the // option even _WANTS_ any more. // bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required; while (NumVals-ValNo > NumPositionalRequired && !Done) { switch (PositionalOpts[i]->getNumOccurrencesFlag()) { case cl::Optional: Done = true; // Optional arguments want _at most_ one value // FALL THROUGH case cl::ZeroOrMore: // Zero or more will take all they can get... case cl::OneOrMore: // One or more will take all they can get... ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first, PositionalVals[ValNo].second); ValNo++; break; default: assert(0 && "Internal error, unexpected NumOccurrences flag in " "positional argument processing!"); abort(); } } } } else { assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size()); unsigned ValNo = 0; for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j) if (RequiresValue(PositionalOpts[j])) { ErrorParsing |= ProvidePositionalOption(PositionalOpts[j], PositionalVals[ValNo].first, PositionalVals[ValNo].second); ValNo++; } // Handle the case where there is just one positional option, and it's // optional. In this case, we want to give JUST THE FIRST option to the // positional option and keep the rest for the consume after. The above // loop would have assigned no values to positional options in this case. // if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) { ErrorParsing |= ProvidePositionalOption(PositionalOpts[1], PositionalVals[ValNo].first, PositionalVals[ValNo].second); ValNo++; } // Handle over all of the rest of the arguments to the // cl::ConsumeAfter command line option... for (; ValNo != PositionalVals.size(); ++ValNo) ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first, PositionalVals[ValNo].second); } // Loop over args and make sure all required args are specified! for (StringMap<Option*>::iterator I = Opts.begin(), E = Opts.end(); I != E; ++I) { switch (I->second->getNumOccurrencesFlag()) { case Required: case OneOrMore: if (I->second->getNumOccurrences() == 0) { I->second->error("must be specified at least once!"); ErrorParsing = true; } // Fall through default: break; } } // Free all of the memory allocated to the map. Command line options may only // be processed once! Opts.clear(); PositionalOpts.clear(); MoreHelp.clear(); // If we had an error processing our arguments, don't let the program execute if (ErrorParsing) exit(1); } //===----------------------------------------------------------------------===// // Option Base class implementation // bool Option::error(const Twine &Message, StringRef ArgName) { if (ArgName.data() == 0) ArgName = ArgStr; if (ArgName.empty()) std::cerr << HelpStr; // Be nice for positional arguments else std::cerr << "for the -" << ArgName.str(); std::cerr << " option: " << Message.str() << "\n"; return true; } bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value, bool MultiArg) { if (!MultiArg) NumOccurrences++; // Increment the number of times we have been seen switch (getNumOccurrencesFlag()) { case Optional: if (NumOccurrences > 1) return error("may only occur zero or one times!", ArgName); break; case Required: if (NumOccurrences > 1) return error("must occur exactly one time!", ArgName); // Fall through case OneOrMore: case ZeroOrMore: case ConsumeAfter: break; default: return error("bad num occurrences flag value!"); } return handleOccurrence(pos, ArgName, Value); } // getValueStr - Get the value description string, using "DefaultMsg" if nothing // has been specified yet. // static const char *getValueStr(const Option &O, const char *DefaultMsg) { if (O.ValueStr[0] == 0) return DefaultMsg; return O.ValueStr; } //===----------------------------------------------------------------------===// // cl::alias class implementation // // Return the width of the option tag for printing... size_t alias::getOptionWidth() const { return std::strlen(ArgStr)+6; } // Print out the option for the alias. void alias::printOptionInfo(size_t GlobalWidth) const { size_t L = std::strlen(ArgStr); std::cout << " -" << ArgStr; std::cout << getIndent(GlobalWidth-L-6) << " - " << HelpStr << "\n"; } //===----------------------------------------------------------------------===// // Parser Implementation code... // // basic_parser implementation // // Return the width of the option tag for printing... size_t basic_parser_impl::getOptionWidth(const Option &O) const { size_t Len = std::strlen(O.ArgStr); if (const char *ValName = getValueName()) Len += std::strlen(getValueStr(O, ValName))+3; return Len + 6; } // printOptionInfo - Print out information about this option. The // to-be-maintained width is specified. // void basic_parser_impl::printOptionInfo(const Option &O, size_t GlobalWidth) const { std::cout << " -" << O.ArgStr; if (const char *ValName = getValueName()) std::cout << "=<" << getValueStr(O, ValName) << '>'; std::cout << getIndent(GlobalWidth-getOptionWidth(O)) << " - " << O.HelpStr << '\n'; } void basic_parser_impl::printOptionName(const Option &O, size_t GlobalWidth) const { std::cout << " -" << O.ArgStr; std::cout << getIndent(GlobalWidth-std::strlen(O.ArgStr)); } // parser<bool> implementation // bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg, bool &Value) { if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" || Arg == "1") { Value = true; return false; } if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") { Value = false; return false; } return O.error("'" + Arg + "' is invalid value for boolean argument! Try 0 or 1"); } // parser<boolOrDefault> implementation // bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg, boolOrDefault &Value) { if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" || Arg == "1") { Value = BOU_TRUE; return false; } if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") { Value = BOU_FALSE; return false; } return O.error("'" + Arg + "' is invalid value for boolean argument! Try 0 or 1"); } // parser<int> implementation // bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg, int &Value) { if (Arg.getAsInteger(0, Value)) return O.error("'" + Arg + "' value invalid for integer argument!"); return false; } // parser<unsigned> implementation // bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg, unsigned &Value) { if (Arg.getAsInteger(0, Value)) return O.error("'" + Arg + "' value invalid for uint argument!"); return false; } // parser<unsigned long long> implementation // bool parser<unsigned long long>::parse(Option &O, StringRef ArgName, StringRef Arg, unsigned long long &Value){ if (Arg.getAsInteger(0, Value)) return O.error("'" + Arg + "' value invalid for uint argument!"); return false; } // parser<double>/parser<float> implementation // static bool parseDouble(Option &O, StringRef Arg, double &Value) { SmallString<32> TmpStr(Arg.begin(), Arg.end()); const char *ArgStart = TmpStr.c_str(); char *End; Value = strtod(ArgStart, &End); if (*End != 0) return O.error("'" + Arg + "' value invalid for floating point argument!"); return false; } bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg, double &Val) { return parseDouble(O, Arg, Val); } bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg, float &Val) { double dVal; if (parseDouble(O, Arg, dVal)) return true; Val = (float)dVal; return false; } // generic_parser_base implementation // // findOption - Return the option number corresponding to the specified // argument string. If the option is not found, getNumOptions() is returned. // unsigned generic_parser_base::findOption(const char *Name) { unsigned e = getNumOptions(); for (unsigned i = 0; i != e; ++i) { if (strcmp(getOption(i), Name) == 0) return i; } return e; } // Return the width of the option tag for printing... size_t generic_parser_base::getOptionWidth(const Option &O) const { if (O.hasArgStr()) { size_t Size = std::strlen(O.ArgStr)+6; for (unsigned i = 0, e = getNumOptions(); i != e; ++i) Size = std::max(Size, std::strlen(getOption(i))+8); return Size; } else { size_t BaseSize = 0; for (unsigned i = 0, e = getNumOptions(); i != e; ++i) BaseSize = std::max(BaseSize, std::strlen(getOption(i))+8); return BaseSize; } } // printOptionInfo - Print out information about this option. The // to-be-maintained width is specified. // void generic_parser_base::printOptionInfo(const Option &O, size_t GlobalWidth) const { if (O.hasArgStr()) { size_t L = std::strlen(O.ArgStr); std::cout << " -" << O.ArgStr; std::cout << getIndent(GlobalWidth-L-6) << " - " << O.HelpStr << '\n'; for (unsigned i = 0, e = getNumOptions(); i != e; ++i) { size_t NumSpaces = GlobalWidth-strlen(getOption(i))-8; std::cout << " =" << getOption(i); std::cout << getIndent(NumSpaces) << " - " << getDescription(i) << '\n'; } } else { if (O.HelpStr[0]) std::cout << " " << O.HelpStr << '\n'; for (unsigned i = 0, e = getNumOptions(); i != e; ++i) { size_t L = std::strlen(getOption(i)); std::cout << " -" << getOption(i); std::cout << getIndent(GlobalWidth-L-8) << " - " << getDescription(i) << '\n'; } } } static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff // printGenericOptionDiff - Print the value of this option and it's default. // // "Generic" options have each value mapped to a name. void generic_parser_base:: printGenericOptionDiff(const Option &O, const GenericOptionValue &Value, const GenericOptionValue &Default, size_t GlobalWidth) const { std::cout << " -" << O.ArgStr; std::cout << getIndent(GlobalWidth-std::strlen(O.ArgStr)); unsigned NumOpts = getNumOptions(); for (unsigned i = 0; i != NumOpts; ++i) { if (Value.compare(getOptionValue(i))) continue; std::cout << "= " << getOption(i); size_t L = std::strlen(getOption(i)); size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0; std::cout << getIndent(NumSpaces) << " (default: "; for (unsigned j = 0; j != NumOpts; ++j) { if (Default.compare(getOptionValue(j))) continue; std::cout << getOption(j); break; } std::cout << ")\n"; return; } std::cout << "= *unknown option value*\n"; } // printOptionDiff - Specializations for printing basic value types. // #define PRINT_OPT_DIFF(T) \ void parser<T>:: \ printOptionDiff(const Option &O, T V, OptionValue<T> D, \ size_t GlobalWidth) const { \ printOptionName(O, GlobalWidth); \ std::stringstream Str; \ Str << V; \ std::cout << "= " << Str.str(); \ size_t NumSpaces = MaxOptWidth > Str.str().size() ? MaxOptWidth - Str.str().size() : 0; \ std::cout << getIndent(NumSpaces) << " (default: "; \ if (D.hasValue()) \ std::cout << D.getValue(); \ else \ std::cout << "*no default*"; \ std::cout << ")\n"; \ } \ PRINT_OPT_DIFF(bool) PRINT_OPT_DIFF(boolOrDefault) PRINT_OPT_DIFF(int) PRINT_OPT_DIFF(unsigned) PRINT_OPT_DIFF(unsigned long long) PRINT_OPT_DIFF(double) PRINT_OPT_DIFF(float) PRINT_OPT_DIFF(char) void parser<std::string>:: printOptionDiff(const Option &O, StringRef V, OptionValue<std::string> D, size_t GlobalWidth) const { printOptionName(O, GlobalWidth); std::cout << "= " << V.str(); size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0; std::cout << getIndent(NumSpaces) << " (default: "; if (D.hasValue()) std::cout << D.getValue(); else std::cout << "*no default*"; std::cout << ")\n"; } // Print a placeholder for options that don't yet support printOptionDiff(). void basic_parser_impl:: printOptionNoValue(const Option &O, size_t GlobalWidth) const { printOptionName(O, GlobalWidth); std::cout << "= *cannot print option value*\n"; } //===----------------------------------------------------------------------===// // -help and -help-hidden option implementation // static int OptNameCompare(const void *LHS, const void *RHS) { typedef std::pair<const char *, Option*> pair_ty; return strcmp(((pair_ty*)LHS)->first, ((pair_ty*)RHS)->first); } // Copy Options into a vector so we can sort them as we like. static void sortOpts(StringMap<Option*> &OptMap, SmallVectorImpl< std::pair<const char *, Option*> > &Opts, bool ShowHidden) { SmallPtrSet<Option*, 128> OptionSet; // Duplicate option detection. for (StringMap<Option*>::iterator I = OptMap.begin(), E = OptMap.end(); I != E; ++I) { // Ignore really-hidden options. if (I->second->getOptionHiddenFlag() == ReallyHidden) continue; // Unless showhidden is set, ignore hidden flags. if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden) continue; // If we've already seen this option, don't add it to the list again. if (!OptionSet.insert(I->second)) continue; Opts.push_back(std::pair<const char *, Option*>(I->getKey().data(), I->second)); } // Sort the options list alphabetically. qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare); } namespace { class HelpPrinter { size_t MaxArgLen; const Option *EmptyArg; const bool ShowHidden; public: explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) { EmptyArg = 0; } void operator=(bool Value) { if (Value == false) return; // Get all the options. SmallVector<Option*, 4> PositionalOpts; SmallVector<Option*, 4> SinkOpts; StringMap<Option*> OptMap; GetOptionInfo(PositionalOpts, SinkOpts, OptMap); SmallVector<std::pair<const char *, Option*>, 128> Opts; sortOpts(OptMap, Opts, ShowHidden); std::cout << "USAGE: "; // Print out the positional options. Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists... if (!PositionalOpts.empty() && PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter) CAOpt = PositionalOpts[0]; for (size_t i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) { if (PositionalOpts[i]->ArgStr[0]) std::cout << " --" << PositionalOpts[i]->ArgStr; std::cout << " " << PositionalOpts[i]->HelpStr; } // Print the consume after option info if it exists... if (CAOpt) std::cout << " " << CAOpt->HelpStr; std::cout << "\n\n"; // Compute the maximum argument length... MaxArgLen = 0; for (size_t i = 0, e = Opts.size(); i != e; ++i) MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth()); std::cout << "OPTIONS:\n"; for (size_t i = 0, e = Opts.size(); i != e; ++i) Opts[i].second->printOptionInfo(MaxArgLen); // Print any extra help the user has declared. for (std::vector<const char *>::iterator I = MoreHelp.begin(), E = MoreHelp.end(); I != E; ++I) std::cout << *I; MoreHelp.clear(); // Halt the program since help information was printed exit(1); } }; } // End anonymous namespace // Define the two HelpPrinter instances that are used to print out help, or // help-hidden... // static HelpPrinter NormalPrinter(false); static HelpPrinter HiddenPrinter(true); static cl::opt<HelpPrinter, true, parser<bool> > HOp("help", cl::desc("Display available options (-help-hidden for more)"), cl::location(NormalPrinter), cl::ValueDisallowed); static cl::opt<HelpPrinter, true, parser<bool> > HHOp("help-hidden", cl::desc("Display all available options"), cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed); static cl::opt<bool> PrintOptions("print-options", cl::desc("Print non-default options after command line parsing"), cl::Hidden, cl::init(false)); static cl::opt<bool> PrintAllOptions("print-all-options", cl::desc("Print all option values after command line parsing"), cl::Hidden, cl::init(false)); // Print the value of each option. void cl::PrintOptionValues() { if (!PrintOptions && !PrintAllOptions) return; // Get all the options. SmallVector<Option*, 4> PositionalOpts; SmallVector<Option*, 4> SinkOpts; StringMap<Option*> OptMap; GetOptionInfo(PositionalOpts, SinkOpts, OptMap); SmallVector<std::pair<const char *, Option*>, 128> Opts; sortOpts(OptMap, Opts, /*ShowHidden*/true); // Compute the maximum argument length... size_t MaxArgLen = 0; for (size_t i = 0, e = Opts.size(); i != e; ++i) MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth()); for (size_t i = 0, e = Opts.size(); i != e; ++i) Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions); } static void (*OverrideVersionPrinter)() = 0; static std::vector<void (*)()>* ExtraVersionPrinters = 0; namespace { class VersionPrinter { public: void print() { //ADL: GALOIS CHANGE std::cout << "Galois Runtime 2.1"; } void operator=(bool OptionWasSpecified) { if (!OptionWasSpecified) return; if (OverrideVersionPrinter != 0) { (*OverrideVersionPrinter)(); exit(1); } print(); // Iterate over any registered extra printers and call them to add further // information. if (ExtraVersionPrinters != 0) { std::cout << '\n'; for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(), E = ExtraVersionPrinters->end(); I != E; ++I) (*I)(); } exit(1); } }; } // End anonymous namespace // Define the --version option that prints out the LLVM version for the tool static VersionPrinter VersionPrinterInstance; static cl::opt<VersionPrinter, true, parser<bool> > VersOp("version", cl::desc("Display the version of this program"), cl::location(VersionPrinterInstance), cl::ValueDisallowed); // Utility function for printing the help message. void cl::PrintHelpMessage() { // This looks weird, but it actually prints the help message. The // NormalPrinter variable is a HelpPrinter and the help gets printed when // its operator= is invoked. That's because the "normal" usages of the // help printer is to be assigned true/false depending on whether the // -help option was given or not. Since we're circumventing that we have // to make it look like -help was given, so we assign true. NormalPrinter = true; } /// Utility function for printing version number. void cl::PrintVersionMessage() { VersionPrinterInstance.print(); } void cl::SetVersionPrinter(void (*func)()) { OverrideVersionPrinter = func; } void cl::AddExtraVersionPrinter(void (*func)()) { if (ExtraVersionPrinters == 0) ExtraVersionPrinters = new std::vector<void (*)()>; ExtraVersionPrinters->push_back(func); }
0
rapidsai_public_repos/code-share/maxflow/galois/src
rapidsai_public_repos/code-share/maxflow/galois/src/llvm/APInt.cpp
//===-- APInt.cpp - Implement APInt class ---------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements a class to represent arbitrary precision integer // constant values and provide a variety of arithmetic operations on them. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "apint" #include "llvm/ADT/APInt.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/MathExtras.h" #include <cmath> #include <limits> #include <cstring> #include <cstdlib> #include <iostream> using namespace llvm; /// A utility function for allocating memory, checking for allocation failures, /// and ensuring the contents are zeroed. inline static uint64_t* getClearedMemory(unsigned numWords) { uint64_t * result = new uint64_t[numWords]; assert(result && "APInt memory allocation fails!"); memset(result, 0, numWords * sizeof(uint64_t)); return result; } /// A utility function for allocating memory and checking for allocation /// failure. The content is not zeroed. inline static uint64_t* getMemory(unsigned numWords) { uint64_t * result = new uint64_t[numWords]; assert(result && "APInt memory allocation fails!"); return result; } /// A utility function that converts a character to a digit. inline static unsigned getDigit(char cdigit, uint8_t radix) { unsigned r; if (radix == 16 || radix == 36) { r = cdigit - '0'; if (r <= 9) return r; r = cdigit - 'A'; if (r <= radix - 11U) return r + 10; r = cdigit - 'a'; if (r <= radix - 11U) return r + 10; radix = 10; } r = cdigit - '0'; if (r < radix) return r; return -1U; } void APInt::initSlowCase(unsigned numBits, uint64_t val, bool isSigned) { pVal = getClearedMemory(getNumWords()); pVal[0] = val; if (isSigned && int64_t(val) < 0) for (unsigned i = 1; i < getNumWords(); ++i) pVal[i] = -1ULL; } void APInt::initSlowCase(const APInt& that) { pVal = getMemory(getNumWords()); memcpy(pVal, that.pVal, getNumWords() * APINT_WORD_SIZE); } void APInt::initFromArray(ArrayRef<uint64_t> bigVal) { assert(BitWidth && "Bitwidth too small"); assert(bigVal.data() && "Null pointer detected!"); if (isSingleWord()) VAL = bigVal[0]; else { // Get memory, cleared to 0 pVal = getClearedMemory(getNumWords()); // Calculate the number of words to copy unsigned words = std::min<unsigned>(bigVal.size(), getNumWords()); // Copy the words from bigVal to pVal memcpy(pVal, bigVal.data(), words * APINT_WORD_SIZE); } // Make sure unused high bits are cleared clearUnusedBits(); } APInt::APInt(unsigned numBits, ArrayRef<uint64_t> bigVal) : BitWidth(numBits), VAL(0) { initFromArray(bigVal); } APInt::APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[]) : BitWidth(numBits), VAL(0) { initFromArray(makeArrayRef(bigVal, numWords)); } APInt::APInt(unsigned numbits, StringRef Str, uint8_t radix) : BitWidth(numbits), VAL(0) { assert(BitWidth && "Bitwidth too small"); fromString(numbits, Str, radix); } APInt& APInt::AssignSlowCase(const APInt& RHS) { // Don't do anything for X = X if (this == &RHS) return *this; if (BitWidth == RHS.getBitWidth()) { // assume same bit-width single-word case is already handled assert(!isSingleWord()); memcpy(pVal, RHS.pVal, getNumWords() * APINT_WORD_SIZE); return *this; } if (isSingleWord()) { // assume case where both are single words is already handled assert(!RHS.isSingleWord()); VAL = 0; pVal = getMemory(RHS.getNumWords()); memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE); } else if (getNumWords() == RHS.getNumWords()) memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE); else if (RHS.isSingleWord()) { delete [] pVal; VAL = RHS.VAL; } else { delete [] pVal; pVal = getMemory(RHS.getNumWords()); memcpy(pVal, RHS.pVal, RHS.getNumWords() * APINT_WORD_SIZE); } BitWidth = RHS.BitWidth; return clearUnusedBits(); } APInt& APInt::operator=(uint64_t RHS) { if (isSingleWord()) VAL = RHS; else { pVal[0] = RHS; memset(pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE); } return clearUnusedBits(); } /// add_1 - This function adds a single "digit" integer, y, to the multiple /// "digit" integer array, x[]. x[] is modified to reflect the addition and /// 1 is returned if there is a carry out, otherwise 0 is returned. /// @returns the carry of the addition. static bool add_1(uint64_t dest[], uint64_t x[], unsigned len, uint64_t y) { for (unsigned i = 0; i < len; ++i) { dest[i] = y + x[i]; if (dest[i] < y) y = 1; // Carry one to next digit. else { y = 0; // No need to carry so exit early break; } } return y; } /// @brief Prefix increment operator. Increments the APInt by one. APInt& APInt::operator++() { if (isSingleWord()) ++VAL; else add_1(pVal, pVal, getNumWords(), 1); return clearUnusedBits(); } /// sub_1 - This function subtracts a single "digit" (64-bit word), y, from /// the multi-digit integer array, x[], propagating the borrowed 1 value until /// no further borrowing is neeeded or it runs out of "digits" in x. The result /// is 1 if "borrowing" exhausted the digits in x, or 0 if x was not exhausted. /// In other words, if y > x then this function returns 1, otherwise 0. /// @returns the borrow out of the subtraction static bool sub_1(uint64_t x[], unsigned len, uint64_t y) { for (unsigned i = 0; i < len; ++i) { uint64_t X = x[i]; x[i] -= y; if (y > X) y = 1; // We have to "borrow 1" from next "digit" else { y = 0; // No need to borrow break; // Remaining digits are unchanged so exit early } } return bool(y); } /// @brief Prefix decrement operator. Decrements the APInt by one. APInt& APInt::operator--() { if (isSingleWord()) --VAL; else sub_1(pVal, getNumWords(), 1); return clearUnusedBits(); } /// add - This function adds the integer array x to the integer array Y and /// places the result in dest. /// @returns the carry out from the addition /// @brief General addition of 64-bit integer arrays static bool add(uint64_t *dest, const uint64_t *x, const uint64_t *y, unsigned len) { bool carry = false; for (unsigned i = 0; i< len; ++i) { uint64_t limit = std::min(x[i],y[i]); // must come first in case dest == x dest[i] = x[i] + y[i] + carry; carry = dest[i] < limit || (carry && dest[i] == limit); } return carry; } /// Adds the RHS APint to this APInt. /// @returns this, after addition of RHS. /// @brief Addition assignment operator. APInt& APInt::operator+=(const APInt& RHS) { assert(BitWidth == RHS.BitWidth && "Bit widths must be the same"); if (isSingleWord()) VAL += RHS.VAL; else { add(pVal, pVal, RHS.pVal, getNumWords()); } return clearUnusedBits(); } /// Subtracts the integer array y from the integer array x /// @returns returns the borrow out. /// @brief Generalized subtraction of 64-bit integer arrays. static bool sub(uint64_t *dest, const uint64_t *x, const uint64_t *y, unsigned len) { bool borrow = false; for (unsigned i = 0; i < len; ++i) { uint64_t x_tmp = borrow ? x[i] - 1 : x[i]; borrow = y[i] > x_tmp || (borrow && x[i] == 0); dest[i] = x_tmp - y[i]; } return borrow; } /// Subtracts the RHS APInt from this APInt /// @returns this, after subtraction /// @brief Subtraction assignment operator. APInt& APInt::operator-=(const APInt& RHS) { assert(BitWidth == RHS.BitWidth && "Bit widths must be the same"); if (isSingleWord()) VAL -= RHS.VAL; else sub(pVal, pVal, RHS.pVal, getNumWords()); return clearUnusedBits(); } /// Multiplies an integer array, x, by a uint64_t integer and places the result /// into dest. /// @returns the carry out of the multiplication. /// @brief Multiply a multi-digit APInt by a single digit (64-bit) integer. static uint64_t mul_1(uint64_t dest[], uint64_t x[], unsigned len, uint64_t y) { // Split y into high 32-bit part (hy) and low 32-bit part (ly) uint64_t ly = y & 0xffffffffULL, hy = y >> 32; uint64_t carry = 0; // For each digit of x. for (unsigned i = 0; i < len; ++i) { // Split x into high and low words uint64_t lx = x[i] & 0xffffffffULL; uint64_t hx = x[i] >> 32; // hasCarry - A flag to indicate if there is a carry to the next digit. // hasCarry == 0, no carry // hasCarry == 1, has carry // hasCarry == 2, no carry and the calculation result == 0. uint8_t hasCarry = 0; dest[i] = carry + lx * ly; // Determine if the add above introduces carry. hasCarry = (dest[i] < carry) ? 1 : 0; carry = hx * ly + (dest[i] >> 32) + (hasCarry ? (1ULL << 32) : 0); // The upper limit of carry can be (2^32 - 1)(2^32 - 1) + // (2^32 - 1) + 2^32 = 2^64. hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0); carry += (lx * hy) & 0xffffffffULL; dest[i] = (carry << 32) | (dest[i] & 0xffffffffULL); carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0) + (carry >> 32) + ((lx * hy) >> 32) + hx * hy; } return carry; } /// Multiplies integer array x by integer array y and stores the result into /// the integer array dest. Note that dest's size must be >= xlen + ylen. /// @brief Generalized multiplicate of integer arrays. static void mul(uint64_t dest[], uint64_t x[], unsigned xlen, uint64_t y[], unsigned ylen) { dest[xlen] = mul_1(dest, x, xlen, y[0]); for (unsigned i = 1; i < ylen; ++i) { uint64_t ly = y[i] & 0xffffffffULL, hy = y[i] >> 32; uint64_t carry = 0, lx = 0, hx = 0; for (unsigned j = 0; j < xlen; ++j) { lx = x[j] & 0xffffffffULL; hx = x[j] >> 32; // hasCarry - A flag to indicate if has carry. // hasCarry == 0, no carry // hasCarry == 1, has carry // hasCarry == 2, no carry and the calculation result == 0. uint8_t hasCarry = 0; uint64_t resul = carry + lx * ly; hasCarry = (resul < carry) ? 1 : 0; carry = (hasCarry ? (1ULL << 32) : 0) + hx * ly + (resul >> 32); hasCarry = (!carry && hasCarry) ? 1 : (!carry ? 2 : 0); carry += (lx * hy) & 0xffffffffULL; resul = (carry << 32) | (resul & 0xffffffffULL); dest[i+j] += resul; carry = (((!carry && hasCarry != 2) || hasCarry == 1) ? (1ULL << 32) : 0)+ (carry >> 32) + (dest[i+j] < resul ? 1 : 0) + ((lx * hy) >> 32) + hx * hy; } dest[i+xlen] = carry; } } APInt& APInt::operator*=(const APInt& RHS) { assert(BitWidth == RHS.BitWidth && "Bit widths must be the same"); if (isSingleWord()) { VAL *= RHS.VAL; clearUnusedBits(); return *this; } // Get some bit facts about LHS and check for zero unsigned lhsBits = getActiveBits(); unsigned lhsWords = !lhsBits ? 0 : whichWord(lhsBits - 1) + 1; if (!lhsWords) // 0 * X ===> 0 return *this; // Get some bit facts about RHS and check for zero unsigned rhsBits = RHS.getActiveBits(); unsigned rhsWords = !rhsBits ? 0 : whichWord(rhsBits - 1) + 1; if (!rhsWords) { // X * 0 ===> 0 clearAllBits(); return *this; } // Allocate space for the result unsigned destWords = rhsWords + lhsWords; uint64_t *dest = getMemory(destWords); // Perform the long multiply mul(dest, pVal, lhsWords, RHS.pVal, rhsWords); // Copy result back into *this clearAllBits(); unsigned wordsToCopy = destWords >= getNumWords() ? getNumWords() : destWords; memcpy(pVal, dest, wordsToCopy * APINT_WORD_SIZE); // delete dest array and return delete[] dest; return *this; } APInt& APInt::operator&=(const APInt& RHS) { assert(BitWidth == RHS.BitWidth && "Bit widths must be the same"); if (isSingleWord()) { VAL &= RHS.VAL; return *this; } unsigned numWords = getNumWords(); for (unsigned i = 0; i < numWords; ++i) pVal[i] &= RHS.pVal[i]; return *this; } APInt& APInt::operator|=(const APInt& RHS) { assert(BitWidth == RHS.BitWidth && "Bit widths must be the same"); if (isSingleWord()) { VAL |= RHS.VAL; return *this; } unsigned numWords = getNumWords(); for (unsigned i = 0; i < numWords; ++i) pVal[i] |= RHS.pVal[i]; return *this; } APInt& APInt::operator^=(const APInt& RHS) { assert(BitWidth == RHS.BitWidth && "Bit widths must be the same"); if (isSingleWord()) { VAL ^= RHS.VAL; this->clearUnusedBits(); return *this; } unsigned numWords = getNumWords(); for (unsigned i = 0; i < numWords; ++i) pVal[i] ^= RHS.pVal[i]; return clearUnusedBits(); } APInt APInt::AndSlowCase(const APInt& RHS) const { unsigned numWords = getNumWords(); uint64_t* val = getMemory(numWords); for (unsigned i = 0; i < numWords; ++i) val[i] = pVal[i] & RHS.pVal[i]; return APInt(val, getBitWidth()); } APInt APInt::OrSlowCase(const APInt& RHS) const { unsigned numWords = getNumWords(); uint64_t *val = getMemory(numWords); for (unsigned i = 0; i < numWords; ++i) val[i] = pVal[i] | RHS.pVal[i]; return APInt(val, getBitWidth()); } APInt APInt::XorSlowCase(const APInt& RHS) const { unsigned numWords = getNumWords(); uint64_t *val = getMemory(numWords); for (unsigned i = 0; i < numWords; ++i) val[i] = pVal[i] ^ RHS.pVal[i]; // 0^0==1 so clear the high bits in case they got set. return APInt(val, getBitWidth()).clearUnusedBits(); } bool APInt::operator !() const { if (isSingleWord()) return !VAL; for (unsigned i = 0; i < getNumWords(); ++i) if (pVal[i]) return false; return true; } APInt APInt::operator*(const APInt& RHS) const { assert(BitWidth == RHS.BitWidth && "Bit widths must be the same"); if (isSingleWord()) return APInt(BitWidth, VAL * RHS.VAL); APInt Result(*this); Result *= RHS; return Result.clearUnusedBits(); } APInt APInt::operator+(const APInt& RHS) const { assert(BitWidth == RHS.BitWidth && "Bit widths must be the same"); if (isSingleWord()) return APInt(BitWidth, VAL + RHS.VAL); APInt Result(BitWidth, 0); add(Result.pVal, this->pVal, RHS.pVal, getNumWords()); return Result.clearUnusedBits(); } APInt APInt::operator-(const APInt& RHS) const { assert(BitWidth == RHS.BitWidth && "Bit widths must be the same"); if (isSingleWord()) return APInt(BitWidth, VAL - RHS.VAL); APInt Result(BitWidth, 0); sub(Result.pVal, this->pVal, RHS.pVal, getNumWords()); return Result.clearUnusedBits(); } bool APInt::operator[](unsigned bitPosition) const { assert(bitPosition < getBitWidth() && "Bit position out of bounds!"); return (maskBit(bitPosition) & (isSingleWord() ? VAL : pVal[whichWord(bitPosition)])) != 0; } bool APInt::EqualSlowCase(const APInt& RHS) const { // Get some facts about the number of bits used in the two operands. unsigned n1 = getActiveBits(); unsigned n2 = RHS.getActiveBits(); // If the number of bits isn't the same, they aren't equal if (n1 != n2) return false; // If the number of bits fits in a word, we only need to compare the low word. if (n1 <= APINT_BITS_PER_WORD) return pVal[0] == RHS.pVal[0]; // Otherwise, compare everything for (int i = whichWord(n1 - 1); i >= 0; --i) if (pVal[i] != RHS.pVal[i]) return false; return true; } bool APInt::EqualSlowCase(uint64_t Val) const { unsigned n = getActiveBits(); if (n <= APINT_BITS_PER_WORD) return pVal[0] == Val; else return false; } bool APInt::ult(const APInt& RHS) const { assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison"); if (isSingleWord()) return VAL < RHS.VAL; // Get active bit length of both operands unsigned n1 = getActiveBits(); unsigned n2 = RHS.getActiveBits(); // If magnitude of LHS is less than RHS, return true. if (n1 < n2) return true; // If magnitude of RHS is greather than LHS, return false. if (n2 < n1) return false; // If they bot fit in a word, just compare the low order word if (n1 <= APINT_BITS_PER_WORD && n2 <= APINT_BITS_PER_WORD) return pVal[0] < RHS.pVal[0]; // Otherwise, compare all words unsigned topWord = whichWord(std::max(n1,n2)-1); for (int i = topWord; i >= 0; --i) { if (pVal[i] > RHS.pVal[i]) return false; if (pVal[i] < RHS.pVal[i]) return true; } return false; } bool APInt::slt(const APInt& RHS) const { assert(BitWidth == RHS.BitWidth && "Bit widths must be same for comparison"); if (isSingleWord()) { int64_t lhsSext = (int64_t(VAL) << (64-BitWidth)) >> (64-BitWidth); int64_t rhsSext = (int64_t(RHS.VAL) << (64-BitWidth)) >> (64-BitWidth); return lhsSext < rhsSext; } APInt lhs(*this); APInt rhs(RHS); bool lhsNeg = isNegative(); bool rhsNeg = rhs.isNegative(); if (lhsNeg) { // Sign bit is set so perform two's complement to make it positive lhs.flipAllBits(); lhs++; } if (rhsNeg) { // Sign bit is set so perform two's complement to make it positive rhs.flipAllBits(); rhs++; } // Now we have unsigned values to compare so do the comparison if necessary // based on the negativeness of the values. if (lhsNeg) if (rhsNeg) return lhs.ugt(rhs); else return true; else if (rhsNeg) return false; else return lhs.ult(rhs); } void APInt::setBit(unsigned bitPosition) { if (isSingleWord()) VAL |= maskBit(bitPosition); else pVal[whichWord(bitPosition)] |= maskBit(bitPosition); } /// Set the given bit to 0 whose position is given as "bitPosition". /// @brief Set a given bit to 0. void APInt::clearBit(unsigned bitPosition) { if (isSingleWord()) VAL &= ~maskBit(bitPosition); else pVal[whichWord(bitPosition)] &= ~maskBit(bitPosition); } /// @brief Toggle every bit to its opposite value. /// Toggle a given bit to its opposite value whose position is given /// as "bitPosition". /// @brief Toggles a given bit to its opposite value. void APInt::flipBit(unsigned bitPosition) { assert(bitPosition < BitWidth && "Out of the bit-width range!"); if ((*this)[bitPosition]) clearBit(bitPosition); else setBit(bitPosition); } unsigned APInt::getBitsNeeded(StringRef str, uint8_t radix) { assert(!str.empty() && "Invalid string length"); assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 || radix == 36) && "Radix should be 2, 8, 10, 16, or 36!"); size_t slen = str.size(); // Each computation below needs to know if it's negative. StringRef::iterator p = str.begin(); unsigned isNegative = *p == '-'; if (*p == '-' || *p == '+') { p++; slen--; assert(slen && "String is only a sign, needs a value."); } // For radixes of power-of-two values, the bits required is accurately and // easily computed if (radix == 2) return slen + isNegative; if (radix == 8) return slen * 3 + isNegative; if (radix == 16) return slen * 4 + isNegative; // FIXME: base 36 // This is grossly inefficient but accurate. We could probably do something // with a computation of roughly slen*64/20 and then adjust by the value of // the first few digits. But, I'm not sure how accurate that could be. // Compute a sufficient number of bits that is always large enough but might // be too large. This avoids the assertion in the constructor. This // calculation doesn't work appropriately for the numbers 0-9, so just use 4 // bits in that case. unsigned sufficient = radix == 10? (slen == 1 ? 4 : slen * 64/18) : (slen == 1 ? 7 : slen * 16/3); // Convert to the actual binary value. APInt tmp(sufficient, StringRef(p, slen), radix); // Compute how many bits are required. If the log is infinite, assume we need // just bit. unsigned log = tmp.logBase2(); if (log == (unsigned)-1) { return isNegative + 1; } else { return isNegative + log + 1; } } // From http://www.burtleburtle.net, byBob Jenkins. // When targeting x86, both GCC and LLVM seem to recognize this as a // rotate instruction. #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k)))) // From http://www.burtleburtle.net, by Bob Jenkins. #define mix(a,b,c) \ { \ a -= c; a ^= rot(c, 4); c += b; \ b -= a; b ^= rot(a, 6); a += c; \ c -= b; c ^= rot(b, 8); b += a; \ a -= c; a ^= rot(c,16); c += b; \ b -= a; b ^= rot(a,19); a += c; \ c -= b; c ^= rot(b, 4); b += a; \ } // From http://www.burtleburtle.net, by Bob Jenkins. #define final(a,b,c) \ { \ c ^= b; c -= rot(b,14); \ a ^= c; a -= rot(c,11); \ b ^= a; b -= rot(a,25); \ c ^= b; c -= rot(b,16); \ a ^= c; a -= rot(c,4); \ b ^= a; b -= rot(a,14); \ c ^= b; c -= rot(b,24); \ } // hashword() was adapted from http://www.burtleburtle.net, by Bob // Jenkins. k is a pointer to an array of uint32_t values; length is // the length of the key, in 32-bit chunks. This version only handles // keys that are a multiple of 32 bits in size. static inline uint32_t hashword(const uint64_t *k64, size_t length) { const uint32_t *k = reinterpret_cast<const uint32_t *>(k64); uint32_t a,b,c; /* Set up the internal state */ a = b = c = 0xdeadbeef + (((uint32_t)length)<<2); /*------------------------------------------------- handle most of the key */ while (length > 3) { a += k[0]; b += k[1]; c += k[2]; mix(a,b,c); length -= 3; k += 3; } /*------------------------------------------- handle the last 3 uint32_t's */ switch (length) { /* all the case statements fall through */ case 3 : c+=k[2]; case 2 : b+=k[1]; case 1 : a+=k[0]; final(a,b,c); case 0: /* case 0: nothing left to add */ break; } /*------------------------------------------------------ report the result */ return c; } // hashword8() was adapted from http://www.burtleburtle.net, by Bob // Jenkins. This computes a 32-bit hash from one 64-bit word. When // targeting x86 (32 or 64 bit), both LLVM and GCC compile this // function into about 35 instructions when inlined. static inline uint32_t hashword8(const uint64_t k64) { uint32_t a,b,c; a = b = c = 0xdeadbeef + 4; b += k64 >> 32; a += k64 & 0xffffffff; final(a,b,c); return c; } #undef final #undef mix #undef rot uint64_t APInt::getHashValue() const { uint64_t hash; if (isSingleWord()) hash = hashword8(VAL); else hash = hashword(pVal, getNumWords()*2); return hash; } /// HiBits - This function returns the high "numBits" bits of this APInt. APInt APInt::getHiBits(unsigned numBits) const { return APIntOps::lshr(*this, BitWidth - numBits); } /// LoBits - This function returns the low "numBits" bits of this APInt. APInt APInt::getLoBits(unsigned numBits) const { return APIntOps::lshr(APIntOps::shl(*this, BitWidth - numBits), BitWidth - numBits); } unsigned APInt::countLeadingZerosSlowCase() const { // Treat the most significand word differently because it might have // meaningless bits set beyond the precision. unsigned BitsInMSW = BitWidth % APINT_BITS_PER_WORD; integerPart MSWMask; if (BitsInMSW) MSWMask = (integerPart(1) << BitsInMSW) - 1; else { MSWMask = ~integerPart(0); BitsInMSW = APINT_BITS_PER_WORD; } unsigned i = getNumWords(); integerPart MSW = pVal[i-1] & MSWMask; if (MSW) return CountLeadingZeros_64(MSW) - (APINT_BITS_PER_WORD - BitsInMSW); unsigned Count = BitsInMSW; for (--i; i > 0u; --i) { if (pVal[i-1] == 0) Count += APINT_BITS_PER_WORD; else { Count += CountLeadingZeros_64(pVal[i-1]); break; } } return Count; } static unsigned countLeadingOnes_64(uint64_t V, unsigned skip) { unsigned Count = 0; if (skip) V <<= skip; while (V && (V & (1ULL << 63))) { Count++; V <<= 1; } return Count; } unsigned APInt::countLeadingOnes() const { if (isSingleWord()) return countLeadingOnes_64(VAL, APINT_BITS_PER_WORD - BitWidth); unsigned highWordBits = BitWidth % APINT_BITS_PER_WORD; unsigned shift; if (!highWordBits) { highWordBits = APINT_BITS_PER_WORD; shift = 0; } else { shift = APINT_BITS_PER_WORD - highWordBits; } int i = getNumWords() - 1; unsigned Count = countLeadingOnes_64(pVal[i], shift); if (Count == highWordBits) { for (i--; i >= 0; --i) { if (pVal[i] == -1ULL) Count += APINT_BITS_PER_WORD; else { Count += countLeadingOnes_64(pVal[i], 0); break; } } } return Count; } unsigned APInt::countTrailingZeros() const { if (isSingleWord()) return std::min(unsigned(CountTrailingZeros_64(VAL)), BitWidth); unsigned Count = 0; unsigned i = 0; for (; i < getNumWords() && pVal[i] == 0; ++i) Count += APINT_BITS_PER_WORD; if (i < getNumWords()) Count += CountTrailingZeros_64(pVal[i]); return std::min(Count, BitWidth); } unsigned APInt::countTrailingOnesSlowCase() const { unsigned Count = 0; unsigned i = 0; for (; i < getNumWords() && pVal[i] == -1ULL; ++i) Count += APINT_BITS_PER_WORD; if (i < getNumWords()) Count += CountTrailingOnes_64(pVal[i]); return std::min(Count, BitWidth); } unsigned APInt::countPopulationSlowCase() const { unsigned Count = 0; for (unsigned i = 0; i < getNumWords(); ++i) Count += CountPopulation_64(pVal[i]); return Count; } APInt APInt::byteSwap() const { assert(BitWidth >= 16 && BitWidth % 16 == 0 && "Cannot byteswap!"); if (BitWidth == 16) return APInt(BitWidth, ByteSwap_16(uint16_t(VAL))); else if (BitWidth == 32) return APInt(BitWidth, ByteSwap_32(unsigned(VAL))); else if (BitWidth == 48) { unsigned Tmp1 = unsigned(VAL >> 16); Tmp1 = ByteSwap_32(Tmp1); uint16_t Tmp2 = uint16_t(VAL); Tmp2 = ByteSwap_16(Tmp2); return APInt(BitWidth, (uint64_t(Tmp2) << 32) | Tmp1); } else if (BitWidth == 64) return APInt(BitWidth, ByteSwap_64(VAL)); else { APInt Result(BitWidth, 0); char *pByte = (char*)Result.pVal; for (unsigned i = 0; i < BitWidth / APINT_WORD_SIZE / 2; ++i) { char Tmp = pByte[i]; pByte[i] = pByte[BitWidth / APINT_WORD_SIZE - 1 - i]; pByte[BitWidth / APINT_WORD_SIZE - i - 1] = Tmp; } return Result; } } APInt llvm::APIntOps::GreatestCommonDivisor(const APInt& API1, const APInt& API2) { APInt A = API1, B = API2; while (!!B) { APInt T = B; B = APIntOps::urem(A, B); A = T; } return A; } APInt llvm::APIntOps::RoundDoubleToAPInt(double Double, unsigned width) { union { double D; uint64_t I; } T; T.D = Double; // Get the sign bit from the highest order bit bool isNeg = T.I >> 63; // Get the 11-bit exponent and adjust for the 1023 bit bias int64_t exp = ((T.I >> 52) & 0x7ff) - 1023; // If the exponent is negative, the value is < 0 so just return 0. if (exp < 0) return APInt(width, 0u); // Extract the mantissa by clearing the top 12 bits (sign + exponent). uint64_t mantissa = (T.I & (~0ULL >> 12)) | 1ULL << 52; // If the exponent doesn't shift all bits out of the mantissa if (exp < 52) return isNeg ? -APInt(width, mantissa >> (52 - exp)) : APInt(width, mantissa >> (52 - exp)); // If the client didn't provide enough bits for us to shift the mantissa into // then the result is undefined, just return 0 if (width <= exp - 52) return APInt(width, 0); // Otherwise, we have to shift the mantissa bits up to the right location APInt Tmp(width, mantissa); Tmp = Tmp.shl((unsigned)exp - 52); return isNeg ? -Tmp : Tmp; } /// RoundToDouble - This function converts this APInt to a double. /// The layout for double is as following (IEEE Standard 754): /// -------------------------------------- /// | Sign Exponent Fraction Bias | /// |-------------------------------------- | /// | 1[63] 11[62-52] 52[51-00] 1023 | /// -------------------------------------- double APInt::roundToDouble(bool isSigned) const { // Handle the simple case where the value is contained in one uint64_t. // It is wrong to optimize getWord(0) to VAL; there might be more than one word. if (isSingleWord() || getActiveBits() <= APINT_BITS_PER_WORD) { if (isSigned) { int64_t sext = (int64_t(getWord(0)) << (64-BitWidth)) >> (64-BitWidth); return double(sext); } else return double(getWord(0)); } // Determine if the value is negative. bool isNeg = isSigned ? (*this)[BitWidth-1] : false; // Construct the absolute value if we're negative. APInt Tmp(isNeg ? -(*this) : (*this)); // Figure out how many bits we're using. unsigned n = Tmp.getActiveBits(); // The exponent (without bias normalization) is just the number of bits // we are using. Note that the sign bit is gone since we constructed the // absolute value. uint64_t exp = n; // Return infinity for exponent overflow if (exp > 1023) { if (!isSigned || !isNeg) return std::numeric_limits<double>::infinity(); else return -std::numeric_limits<double>::infinity(); } exp += 1023; // Increment for 1023 bias // Number of bits in mantissa is 52. To obtain the mantissa value, we must // extract the high 52 bits from the correct words in pVal. uint64_t mantissa; unsigned hiWord = whichWord(n-1); if (hiWord == 0) { mantissa = Tmp.pVal[0]; if (n > 52) mantissa >>= n - 52; // shift down, we want the top 52 bits. } else { assert(hiWord > 0 && "huh?"); uint64_t hibits = Tmp.pVal[hiWord] << (52 - n % APINT_BITS_PER_WORD); uint64_t lobits = Tmp.pVal[hiWord-1] >> (11 + n % APINT_BITS_PER_WORD); mantissa = hibits | lobits; } // The leading bit of mantissa is implicit, so get rid of it. uint64_t sign = isNeg ? (1ULL << (APINT_BITS_PER_WORD - 1)) : 0; union { double D; uint64_t I; } T; T.I = sign | (exp << 52) | mantissa; return T.D; } // Truncate to new width. APInt APInt::trunc(unsigned width) const { assert(width < BitWidth && "Invalid APInt Truncate request"); assert(width && "Can't truncate to 0 bits"); if (width <= APINT_BITS_PER_WORD) return APInt(width, getRawData()[0]); APInt Result(getMemory(getNumWords(width)), width); // Copy full words. unsigned i; for (i = 0; i != width / APINT_BITS_PER_WORD; i++) Result.pVal[i] = pVal[i]; // Truncate and copy any partial word. unsigned bits = (0 - width) % APINT_BITS_PER_WORD; if (bits != 0) Result.pVal[i] = pVal[i] << bits >> bits; return Result; } // Sign extend to a new width. APInt APInt::sext(unsigned width) const { assert(width > BitWidth && "Invalid APInt SignExtend request"); if (width <= APINT_BITS_PER_WORD) { uint64_t val = VAL << (APINT_BITS_PER_WORD - BitWidth); val = (int64_t)val >> (width - BitWidth); return APInt(width, val >> (APINT_BITS_PER_WORD - width)); } APInt Result(getMemory(getNumWords(width)), width); // Copy full words. unsigned i; uint64_t word = 0; for (i = 0; i != BitWidth / APINT_BITS_PER_WORD; i++) { word = getRawData()[i]; Result.pVal[i] = word; } // Read and sign-extend any partial word. unsigned bits = (0 - BitWidth) % APINT_BITS_PER_WORD; if (bits != 0) word = (int64_t)getRawData()[i] << bits >> bits; else word = (int64_t)word >> (APINT_BITS_PER_WORD - 1); // Write remaining full words. for (; i != width / APINT_BITS_PER_WORD; i++) { Result.pVal[i] = word; word = (int64_t)word >> (APINT_BITS_PER_WORD - 1); } // Write any partial word. bits = (0 - width) % APINT_BITS_PER_WORD; if (bits != 0) Result.pVal[i] = word << bits >> bits; return Result; } // Zero extend to a new width. APInt APInt::zext(unsigned width) const { assert(width > BitWidth && "Invalid APInt ZeroExtend request"); if (width <= APINT_BITS_PER_WORD) return APInt(width, VAL); APInt Result(getMemory(getNumWords(width)), width); // Copy words. unsigned i; for (i = 0; i != getNumWords(); i++) Result.pVal[i] = getRawData()[i]; // Zero remaining words. memset(&Result.pVal[i], 0, (Result.getNumWords() - i) * APINT_WORD_SIZE); return Result; } APInt APInt::zextOrTrunc(unsigned width) const { if (BitWidth < width) return zext(width); if (BitWidth > width) return trunc(width); return *this; } APInt APInt::sextOrTrunc(unsigned width) const { if (BitWidth < width) return sext(width); if (BitWidth > width) return trunc(width); return *this; } /// Arithmetic right-shift this APInt by shiftAmt. /// @brief Arithmetic right-shift function. APInt APInt::ashr(const APInt &shiftAmt) const { return ashr((unsigned)shiftAmt.getLimitedValue(BitWidth)); } /// Arithmetic right-shift this APInt by shiftAmt. /// @brief Arithmetic right-shift function. APInt APInt::ashr(unsigned shiftAmt) const { assert(shiftAmt <= BitWidth && "Invalid shift amount"); // Handle a degenerate case if (shiftAmt == 0) return *this; // Handle single word shifts with built-in ashr if (isSingleWord()) { if (shiftAmt == BitWidth) return APInt(BitWidth, 0); // undefined else { unsigned SignBit = APINT_BITS_PER_WORD - BitWidth; return APInt(BitWidth, (((int64_t(VAL) << SignBit) >> SignBit) >> shiftAmt)); } } // If all the bits were shifted out, the result is, technically, undefined. // We return -1 if it was negative, 0 otherwise. We check this early to avoid // issues in the algorithm below. if (shiftAmt == BitWidth) { if (isNegative()) return APInt(BitWidth, -1ULL, true); else return APInt(BitWidth, 0); } // Create some space for the result. uint64_t * val = new uint64_t[getNumWords()]; // Compute some values needed by the following shift algorithms unsigned wordShift = shiftAmt % APINT_BITS_PER_WORD; // bits to shift per word unsigned offset = shiftAmt / APINT_BITS_PER_WORD; // word offset for shift unsigned breakWord = getNumWords() - 1 - offset; // last word affected unsigned bitsInWord = whichBit(BitWidth); // how many bits in last word? if (bitsInWord == 0) bitsInWord = APINT_BITS_PER_WORD; // If we are shifting whole words, just move whole words if (wordShift == 0) { // Move the words containing significant bits for (unsigned i = 0; i <= breakWord; ++i) val[i] = pVal[i+offset]; // move whole word // Adjust the top significant word for sign bit fill, if negative if (isNegative()) if (bitsInWord < APINT_BITS_PER_WORD) val[breakWord] |= ~0ULL << bitsInWord; // set high bits } else { // Shift the low order words for (unsigned i = 0; i < breakWord; ++i) { // This combines the shifted corresponding word with the low bits from // the next word (shifted into this word's high bits). val[i] = (pVal[i+offset] >> wordShift) | (pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift)); } // Shift the break word. In this case there are no bits from the next word // to include in this word. val[breakWord] = pVal[breakWord+offset] >> wordShift; // Deal with sign extenstion in the break word, and possibly the word before // it. if (isNegative()) { if (wordShift > bitsInWord) { if (breakWord > 0) val[breakWord-1] |= ~0ULL << (APINT_BITS_PER_WORD - (wordShift - bitsInWord)); val[breakWord] |= ~0ULL; } else val[breakWord] |= (~0ULL << (bitsInWord - wordShift)); } } // Remaining words are 0 or -1, just assign them. uint64_t fillValue = (isNegative() ? -1ULL : 0); for (unsigned i = breakWord+1; i < getNumWords(); ++i) val[i] = fillValue; return APInt(val, BitWidth).clearUnusedBits(); } /// Logical right-shift this APInt by shiftAmt. /// @brief Logical right-shift function. APInt APInt::lshr(const APInt &shiftAmt) const { return lshr((unsigned)shiftAmt.getLimitedValue(BitWidth)); } /// Logical right-shift this APInt by shiftAmt. /// @brief Logical right-shift function. APInt APInt::lshr(unsigned shiftAmt) const { if (isSingleWord()) { if (shiftAmt == BitWidth) return APInt(BitWidth, 0); else return APInt(BitWidth, this->VAL >> shiftAmt); } // If all the bits were shifted out, the result is 0. This avoids issues // with shifting by the size of the integer type, which produces undefined // results. We define these "undefined results" to always be 0. if (shiftAmt == BitWidth) return APInt(BitWidth, 0); // If none of the bits are shifted out, the result is *this. This avoids // issues with shifting by the size of the integer type, which produces // undefined results in the code below. This is also an optimization. if (shiftAmt == 0) return *this; // Create some space for the result. uint64_t * val = new uint64_t[getNumWords()]; // If we are shifting less than a word, compute the shift with a simple carry if (shiftAmt < APINT_BITS_PER_WORD) { uint64_t carry = 0; for (int i = getNumWords()-1; i >= 0; --i) { val[i] = (pVal[i] >> shiftAmt) | carry; carry = pVal[i] << (APINT_BITS_PER_WORD - shiftAmt); } return APInt(val, BitWidth).clearUnusedBits(); } // Compute some values needed by the remaining shift algorithms unsigned wordShift = shiftAmt % APINT_BITS_PER_WORD; unsigned offset = shiftAmt / APINT_BITS_PER_WORD; // If we are shifting whole words, just move whole words if (wordShift == 0) { for (unsigned i = 0; i < getNumWords() - offset; ++i) val[i] = pVal[i+offset]; for (unsigned i = getNumWords()-offset; i < getNumWords(); i++) val[i] = 0; return APInt(val,BitWidth).clearUnusedBits(); } // Shift the low order words unsigned breakWord = getNumWords() - offset -1; for (unsigned i = 0; i < breakWord; ++i) val[i] = (pVal[i+offset] >> wordShift) | (pVal[i+offset+1] << (APINT_BITS_PER_WORD - wordShift)); // Shift the break word. val[breakWord] = pVal[breakWord+offset] >> wordShift; // Remaining words are 0 for (unsigned i = breakWord+1; i < getNumWords(); ++i) val[i] = 0; return APInt(val, BitWidth).clearUnusedBits(); } /// Left-shift this APInt by shiftAmt. /// @brief Left-shift function. APInt APInt::shl(const APInt &shiftAmt) const { // It's undefined behavior in C to shift by BitWidth or greater. return shl((unsigned)shiftAmt.getLimitedValue(BitWidth)); } APInt APInt::shlSlowCase(unsigned shiftAmt) const { // If all the bits were shifted out, the result is 0. This avoids issues // with shifting by the size of the integer type, which produces undefined // results. We define these "undefined results" to always be 0. if (shiftAmt == BitWidth) return APInt(BitWidth, 0); // If none of the bits are shifted out, the result is *this. This avoids a // lshr by the words size in the loop below which can produce incorrect // results. It also avoids the expensive computation below for a common case. if (shiftAmt == 0) return *this; // Create some space for the result. uint64_t * val = new uint64_t[getNumWords()]; // If we are shifting less than a word, do it the easy way if (shiftAmt < APINT_BITS_PER_WORD) { uint64_t carry = 0; for (unsigned i = 0; i < getNumWords(); i++) { val[i] = pVal[i] << shiftAmt | carry; carry = pVal[i] >> (APINT_BITS_PER_WORD - shiftAmt); } return APInt(val, BitWidth).clearUnusedBits(); } // Compute some values needed by the remaining shift algorithms unsigned wordShift = shiftAmt % APINT_BITS_PER_WORD; unsigned offset = shiftAmt / APINT_BITS_PER_WORD; // If we are shifting whole words, just move whole words if (wordShift == 0) { for (unsigned i = 0; i < offset; i++) val[i] = 0; for (unsigned i = offset; i < getNumWords(); i++) val[i] = pVal[i-offset]; return APInt(val,BitWidth).clearUnusedBits(); } // Copy whole words from this to Result. unsigned i = getNumWords() - 1; for (; i > offset; --i) val[i] = pVal[i-offset] << wordShift | pVal[i-offset-1] >> (APINT_BITS_PER_WORD - wordShift); val[offset] = pVal[0] << wordShift; for (i = 0; i < offset; ++i) val[i] = 0; return APInt(val, BitWidth).clearUnusedBits(); } APInt APInt::rotl(const APInt &rotateAmt) const { return rotl((unsigned)rotateAmt.getLimitedValue(BitWidth)); } APInt APInt::rotl(unsigned rotateAmt) const { if (rotateAmt == 0) return *this; // Don't get too fancy, just use existing shift/or facilities APInt hi(*this); APInt lo(*this); hi.shl(rotateAmt); lo.lshr(BitWidth - rotateAmt); return hi | lo; } APInt APInt::rotr(const APInt &rotateAmt) const { return rotr((unsigned)rotateAmt.getLimitedValue(BitWidth)); } APInt APInt::rotr(unsigned rotateAmt) const { if (rotateAmt == 0) return *this; // Don't get too fancy, just use existing shift/or facilities APInt hi(*this); APInt lo(*this); lo.lshr(rotateAmt); hi.shl(BitWidth - rotateAmt); return hi | lo; } // Square Root - this method computes and returns the square root of "this". // Three mechanisms are used for computation. For small values (<= 5 bits), // a table lookup is done. This gets some performance for common cases. For // values using less than 52 bits, the value is converted to double and then // the libc sqrt function is called. The result is rounded and then converted // back to a uint64_t which is then used to construct the result. Finally, // the Babylonian method for computing square roots is used. APInt APInt::sqrt() const { // Determine the magnitude of the value. unsigned magnitude = getActiveBits(); // Use a fast table for some small values. This also gets rid of some // rounding errors in libc sqrt for small values. if (magnitude <= 5) { static const uint8_t results[32] = { /* 0 */ 0, /* 1- 2 */ 1, 1, /* 3- 6 */ 2, 2, 2, 2, /* 7-12 */ 3, 3, 3, 3, 3, 3, /* 13-20 */ 4, 4, 4, 4, 4, 4, 4, 4, /* 21-30 */ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, /* 31 */ 6 }; return APInt(BitWidth, results[ (isSingleWord() ? VAL : pVal[0]) ]); } // If the magnitude of the value fits in less than 52 bits (the precision of // an IEEE double precision floating point value), then we can use the // libc sqrt function which will probably use a hardware sqrt computation. // This should be faster than the algorithm below. if (magnitude < 52) { #if HAVE_ROUND return APInt(BitWidth, uint64_t(::round(::sqrt(double(isSingleWord()?VAL:pVal[0]))))); #else return APInt(BitWidth, uint64_t(::sqrt(double(isSingleWord()?VAL:pVal[0])) + 0.5)); #endif } // Okay, all the short cuts are exhausted. We must compute it. The following // is a classical Babylonian method for computing the square root. This code // was adapted to APINt from a wikipedia article on such computations. // See http://www.wikipedia.org/ and go to the page named // Calculate_an_integer_square_root. unsigned nbits = BitWidth, i = 4; APInt testy(BitWidth, 16); APInt x_old(BitWidth, 1); APInt x_new(BitWidth, 0); APInt two(BitWidth, 2); // Select a good starting value using binary logarithms. for (;; i += 2, testy = testy.shl(2)) if (i >= nbits || this->ule(testy)) { x_old = x_old.shl(i / 2); break; } // Use the Babylonian method to arrive at the integer square root: for (;;) { x_new = (this->udiv(x_old) + x_old).udiv(two); if (x_old.ule(x_new)) break; x_old = x_new; } // Make sure we return the closest approximation // NOTE: The rounding calculation below is correct. It will produce an // off-by-one discrepancy with results from pari/gp. That discrepancy has been // determined to be a rounding issue with pari/gp as it begins to use a // floating point representation after 192 bits. There are no discrepancies // between this algorithm and pari/gp for bit widths < 192 bits. APInt square(x_old * x_old); APInt nextSquare((x_old + 1) * (x_old +1)); if (this->ult(square)) return x_old; else if (this->ule(nextSquare)) { APInt midpoint((nextSquare - square).udiv(two)); APInt offset(*this - square); if (offset.ult(midpoint)) return x_old; else return x_old + 1; } else abort();//llvm_unreachable("Error in APInt::sqrt computation"); return x_old + 1; } /// Computes the multiplicative inverse of this APInt for a given modulo. The /// iterative extended Euclidean algorithm is used to solve for this value, /// however we simplify it to speed up calculating only the inverse, and take /// advantage of div+rem calculations. We also use some tricks to avoid copying /// (potentially large) APInts around. APInt APInt::multiplicativeInverse(const APInt& modulo) const { assert(ult(modulo) && "This APInt must be smaller than the modulo"); // Using the properties listed at the following web page (accessed 06/21/08): // http://www.numbertheory.org/php/euclid.html // (especially the properties numbered 3, 4 and 9) it can be proved that // BitWidth bits suffice for all the computations in the algorithm implemented // below. More precisely, this number of bits suffice if the multiplicative // inverse exists, but may not suffice for the general extended Euclidean // algorithm. APInt r[2] = { modulo, *this }; APInt t[2] = { APInt(BitWidth, 0), APInt(BitWidth, 1) }; APInt q(BitWidth, 0); unsigned i; for (i = 0; r[i^1] != 0; i ^= 1) { // An overview of the math without the confusing bit-flipping: // q = r[i-2] / r[i-1] // r[i] = r[i-2] % r[i-1] // t[i] = t[i-2] - t[i-1] * q udivrem(r[i], r[i^1], q, r[i]); t[i] -= t[i^1] * q; } // If this APInt and the modulo are not coprime, there is no multiplicative // inverse, so return 0. We check this by looking at the next-to-last // remainder, which is the gcd(*this,modulo) as calculated by the Euclidean // algorithm. if (r[i] != 1) return APInt(BitWidth, 0); // The next-to-last t is the multiplicative inverse. However, we are // interested in a positive inverse. Calcuate a positive one from a negative // one if necessary. A simple addition of the modulo suffices because // abs(t[i]) is known to be less than *this/2 (see the link above). return t[i].isNegative() ? t[i] + modulo : t[i]; } /// Calculate the magic numbers required to implement a signed integer division /// by a constant as a sequence of multiplies, adds and shifts. Requires that /// the divisor not be 0, 1, or -1. Taken from "Hacker's Delight", Henry S. /// Warren, Jr., chapter 10. APInt::ms APInt::magic() const { const APInt& d = *this; unsigned p; APInt ad, anc, delta, q1, r1, q2, r2, t; APInt signedMin = APInt::getSignedMinValue(d.getBitWidth()); struct ms mag; ad = d.abs(); t = signedMin + (d.lshr(d.getBitWidth() - 1)); anc = t - 1 - t.urem(ad); // absolute value of nc p = d.getBitWidth() - 1; // initialize p q1 = signedMin.udiv(anc); // initialize q1 = 2p/abs(nc) r1 = signedMin - q1*anc; // initialize r1 = rem(2p,abs(nc)) q2 = signedMin.udiv(ad); // initialize q2 = 2p/abs(d) r2 = signedMin - q2*ad; // initialize r2 = rem(2p,abs(d)) do { p = p + 1; q1 = q1<<1; // update q1 = 2p/abs(nc) r1 = r1<<1; // update r1 = rem(2p/abs(nc)) if (r1.uge(anc)) { // must be unsigned comparison q1 = q1 + 1; r1 = r1 - anc; } q2 = q2<<1; // update q2 = 2p/abs(d) r2 = r2<<1; // update r2 = rem(2p/abs(d)) if (r2.uge(ad)) { // must be unsigned comparison q2 = q2 + 1; r2 = r2 - ad; } delta = ad - r2; } while (q1.ult(delta) || (q1 == delta && r1 == 0)); mag.m = q2 + 1; if (d.isNegative()) mag.m = -mag.m; // resulting magic number mag.s = p - d.getBitWidth(); // resulting shift return mag; } /// Calculate the magic numbers required to implement an unsigned integer /// division by a constant as a sequence of multiplies, adds and shifts. /// Requires that the divisor not be 0. Taken from "Hacker's Delight", Henry /// S. Warren, Jr., chapter 10. /// LeadingZeros can be used to simplify the calculation if the upper bits /// of the divided value are known zero. APInt::mu APInt::magicu(unsigned LeadingZeros) const { const APInt& d = *this; unsigned p; APInt nc, delta, q1, r1, q2, r2; struct mu magu; magu.a = 0; // initialize "add" indicator APInt allOnes = APInt::getAllOnesValue(d.getBitWidth()).lshr(LeadingZeros); APInt signedMin = APInt::getSignedMinValue(d.getBitWidth()); APInt signedMax = APInt::getSignedMaxValue(d.getBitWidth()); nc = allOnes - (-d).urem(d); p = d.getBitWidth() - 1; // initialize p q1 = signedMin.udiv(nc); // initialize q1 = 2p/nc r1 = signedMin - q1*nc; // initialize r1 = rem(2p,nc) q2 = signedMax.udiv(d); // initialize q2 = (2p-1)/d r2 = signedMax - q2*d; // initialize r2 = rem((2p-1),d) do { p = p + 1; if (r1.uge(nc - r1)) { q1 = q1 + q1 + 1; // update q1 r1 = r1 + r1 - nc; // update r1 } else { q1 = q1+q1; // update q1 r1 = r1+r1; // update r1 } if ((r2 + 1).uge(d - r2)) { if (q2.uge(signedMax)) magu.a = 1; q2 = q2+q2 + 1; // update q2 r2 = r2+r2 + 1 - d; // update r2 } else { if (q2.uge(signedMin)) magu.a = 1; q2 = q2+q2; // update q2 r2 = r2+r2 + 1; // update r2 } delta = d - 1 - r2; } while (p < d.getBitWidth()*2 && (q1.ult(delta) || (q1 == delta && r1 == 0))); magu.m = q2 + 1; // resulting magic number magu.s = p - d.getBitWidth(); // resulting shift return magu; } /// Implementation of Knuth's Algorithm D (Division of nonnegative integers) /// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The /// variables here have the same names as in the algorithm. Comments explain /// the algorithm and any deviation from it. static void KnuthDiv(unsigned *u, unsigned *v, unsigned *q, unsigned* r, unsigned m, unsigned n) { assert(u && "Must provide dividend"); assert(v && "Must provide divisor"); assert(q && "Must provide quotient"); assert(u != v && u != q && v != q && "Must us different memory"); assert(n>1 && "n must be > 1"); // Knuth uses the value b as the base of the number system. In our case b // is 2^31 so we just set it to -1u. uint64_t b = uint64_t(1) << 32; #if 0 DEBUG(dbgs() << "KnuthDiv: m=" << m << " n=" << n << '\n'); DEBUG(dbgs() << "KnuthDiv: original:"); DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]); DEBUG(dbgs() << " by"); DEBUG(for (int i = n; i >0; i--) dbgs() << " " << v[i-1]); DEBUG(dbgs() << '\n'); #endif // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of // u and v by d. Note that we have taken Knuth's advice here to use a power // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of // 2 allows us to shift instead of multiply and it is easy to determine the // shift amount from the leading zeros. We are basically normalizing the u // and v so that its high bits are shifted to the top of v's range without // overflow. Note that this can require an extra word in u so that u must // be of length m+n+1. unsigned shift = CountLeadingZeros_32(v[n-1]); unsigned v_carry = 0; unsigned u_carry = 0; if (shift) { for (unsigned i = 0; i < m+n; ++i) { unsigned u_tmp = u[i] >> (32 - shift); u[i] = (u[i] << shift) | u_carry; u_carry = u_tmp; } for (unsigned i = 0; i < n; ++i) { unsigned v_tmp = v[i] >> (32 - shift); v[i] = (v[i] << shift) | v_carry; v_carry = v_tmp; } } u[m+n] = u_carry; #if 0 DEBUG(dbgs() << "KnuthDiv: normal:"); DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]); DEBUG(dbgs() << " by"); DEBUG(for (int i = n; i >0; i--) dbgs() << " " << v[i-1]); DEBUG(dbgs() << '\n'); #endif // D2. [Initialize j.] Set j to m. This is the loop counter over the places. int j = m; do { //DEBUG(dbgs() << "KnuthDiv: quotient digit #" << j << '\n'); // D3. [Calculate q'.]. // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q') // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r') // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease // qp by 1, inrease rp by v[n-1], and repeat this test if rp < b. The test // on v[n-2] determines at high speed most of the cases in which the trial // value qp is one too large, and it eliminates all cases where qp is two // too large. uint64_t dividend = ((uint64_t(u[j+n]) << 32) + u[j+n-1]); //DEBUG(dbgs() << "KnuthDiv: dividend == " << dividend << '\n'); uint64_t qp = dividend / v[n-1]; uint64_t rp = dividend % v[n-1]; if (qp == b || qp*v[n-2] > b*rp + u[j+n-2]) { qp--; rp += v[n-1]; if (rp < b && (qp == b || qp*v[n-2] > b*rp + u[j+n-2])) qp--; } //DEBUG(dbgs() << "KnuthDiv: qp == " << qp << ", rp == " << rp << '\n'); // D4. [Multiply and subtract.] Replace (u[j+n]u[j+n-1]...u[j]) with // (u[j+n]u[j+n-1]..u[j]) - qp * (v[n-1]...v[1]v[0]). This computation // consists of a simple multiplication by a one-place number, combined with // a subtraction. bool isNeg = false; for (unsigned i = 0; i < n; ++i) { uint64_t u_tmp = uint64_t(u[j+i]) | (uint64_t(u[j+i+1]) << 32); uint64_t subtrahend = uint64_t(qp) * uint64_t(v[i]); bool borrow = subtrahend > u_tmp; // DEBUG(dbgs() << "KnuthDiv: u_tmp == " << u_tmp // << ", subtrahend == " << subtrahend // << ", borrow = " << borrow << '\n'); uint64_t result = u_tmp - subtrahend; unsigned k = j + i; u[k++] = (unsigned)(result & (b-1)); // subtract low word u[k++] = (unsigned)(result >> 32); // subtract high word while (borrow && k <= m+n) { // deal with borrow to the left borrow = u[k] == 0; u[k]--; k++; } isNeg |= borrow; // DEBUG(dbgs() << "KnuthDiv: u[j+i] == " << u[j+i] << ", u[j+i+1] == " << // u[j+i+1] << '\n'); } // DEBUG(dbgs() << "KnuthDiv: after subtraction:"); // DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]); // DEBUG(dbgs() << '\n'); // The digits (u[j+n]...u[j]) should be kept positive; if the result of // this step is actually negative, (u[j+n]...u[j]) should be left as the // true value plus b**(n+1), namely as the b's complement of // the true value, and a "borrow" to the left should be remembered. // if (isNeg) { bool carry = true; // true because b's complement is "complement + 1" for (unsigned i = 0; i <= m+n; ++i) { u[i] = ~u[i] + carry; // b's complement carry = carry && u[i] == 0; } } // DEBUG(dbgs() << "KnuthDiv: after complement:"); // DEBUG(for (int i = m+n; i >=0; i--) dbgs() << " " << u[i]); // DEBUG(dbgs() << '\n'); // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was // negative, go to step D6; otherwise go on to step D7. q[j] = (unsigned)qp; if (isNeg) { // D6. [Add back]. The probability that this step is necessary is very // small, on the order of only 2/b. Make sure that test data accounts for // this possibility. Decrease q[j] by 1 q[j]--; // and add (0v[n-1]...v[1]v[0]) to (u[j+n]u[j+n-1]...u[j+1]u[j]). // A carry will occur to the left of u[j+n], and it should be ignored // since it cancels with the borrow that occurred in D4. bool carry = false; for (unsigned i = 0; i < n; i++) { unsigned limit = std::min(u[j+i],v[i]); u[j+i] += v[i] + carry; carry = u[j+i] < limit || (carry && u[j+i] == limit); } u[j+n] += carry; } // DEBUG(dbgs() << "KnuthDiv: after correction:"); // DEBUG(for (int i = m+n; i >=0; i--) dbgs() <<" " << u[i]); // DEBUG(dbgs() << "\nKnuthDiv: digit result = " << q[j] << '\n'); // D7. [Loop on j.] Decrease j by one. Now if j >= 0, go back to D3. } while (--j >= 0); // DEBUG(dbgs() << "KnuthDiv: quotient:"); // DEBUG(for (int i = m; i >=0; i--) dbgs() <<" " << q[i]); // DEBUG(dbgs() << '\n'); // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired // remainder may be obtained by dividing u[...] by d. If r is non-null we // compute the remainder (urem uses this). if (r) { // The value d is expressed by the "shift" value above since we avoided // multiplication by d by using a shift left. So, all we have to do is // shift right here. In order to mak if (shift) { unsigned carry = 0; // DEBUG(dbgs() << "KnuthDiv: remainder:"); for (int i = n-1; i >= 0; i--) { r[i] = (u[i] >> shift) | carry; carry = u[i] << (32 - shift); // DEBUG(dbgs() << " " << r[i]); } } else { for (int i = n-1; i >= 0; i--) { r[i] = u[i]; // DEBUG(dbgs() << " " << r[i]); } } // DEBUG(dbgs() << '\n'); } #if 0 DEBUG(dbgs() << '\n'); #endif } void APInt::divide(const APInt LHS, unsigned lhsWords, const APInt &RHS, unsigned rhsWords, APInt *Quotient, APInt *Remainder) { assert(lhsWords >= rhsWords && "Fractional result"); // First, compose the values into an array of 32-bit words instead of // 64-bit words. This is a necessity of both the "short division" algorithm // and the Knuth "classical algorithm" which requires there to be native // operations for +, -, and * on an m bit value with an m*2 bit result. We // can't use 64-bit operands here because we don't have native results of // 128-bits. Furthermore, casting the 64-bit values to 32-bit values won't // work on large-endian machines. uint64_t mask = ~0ull >> (sizeof(unsigned)*CHAR_BIT); unsigned n = rhsWords * 2; unsigned m = (lhsWords * 2) - n; // Allocate space for the temporary values we need either on the stack, if // it will fit, or on the heap if it won't. unsigned SPACE[128]; unsigned *U = 0; unsigned *V = 0; unsigned *Q = 0; unsigned *R = 0; if ((Remainder?4:3)*n+2*m+1 <= 128) { U = &SPACE[0]; V = &SPACE[m+n+1]; Q = &SPACE[(m+n+1) + n]; if (Remainder) R = &SPACE[(m+n+1) + n + (m+n)]; } else { U = new unsigned[m + n + 1]; V = new unsigned[n]; Q = new unsigned[m+n]; if (Remainder) R = new unsigned[n]; } // Initialize the dividend memset(U, 0, (m+n+1)*sizeof(unsigned)); for (unsigned i = 0; i < lhsWords; ++i) { uint64_t tmp = (LHS.getNumWords() == 1 ? LHS.VAL : LHS.pVal[i]); U[i * 2] = (unsigned)(tmp & mask); U[i * 2 + 1] = (unsigned)(tmp >> (sizeof(unsigned)*CHAR_BIT)); } U[m+n] = 0; // this extra word is for "spill" in the Knuth algorithm. // Initialize the divisor memset(V, 0, (n)*sizeof(unsigned)); for (unsigned i = 0; i < rhsWords; ++i) { uint64_t tmp = (RHS.getNumWords() == 1 ? RHS.VAL : RHS.pVal[i]); V[i * 2] = (unsigned)(tmp & mask); V[i * 2 + 1] = (unsigned)(tmp >> (sizeof(unsigned)*CHAR_BIT)); } // initialize the quotient and remainder memset(Q, 0, (m+n) * sizeof(unsigned)); if (Remainder) memset(R, 0, n * sizeof(unsigned)); // Now, adjust m and n for the Knuth division. n is the number of words in // the divisor. m is the number of words by which the dividend exceeds the // divisor (i.e. m+n is the length of the dividend). These sizes must not // contain any zero words or the Knuth algorithm fails. for (unsigned i = n; i > 0 && V[i-1] == 0; i--) { n--; m++; } for (unsigned i = m+n; i > 0 && U[i-1] == 0; i--) m--; // If we're left with only a single word for the divisor, Knuth doesn't work // so we implement the short division algorithm here. This is much simpler // and faster because we are certain that we can divide a 64-bit quantity // by a 32-bit quantity at hardware speed and short division is simply a // series of such operations. This is just like doing short division but we // are using base 2^32 instead of base 10. assert(n != 0 && "Divide by zero?"); if (n == 1) { unsigned divisor = V[0]; unsigned remainder = 0; for (int i = m+n-1; i >= 0; i--) { uint64_t partial_dividend = uint64_t(remainder) << 32 | U[i]; if (partial_dividend == 0) { Q[i] = 0; remainder = 0; } else if (partial_dividend < divisor) { Q[i] = 0; remainder = (unsigned)partial_dividend; } else if (partial_dividend == divisor) { Q[i] = 1; remainder = 0; } else { Q[i] = (unsigned)(partial_dividend / divisor); remainder = (unsigned)(partial_dividend - (Q[i] * divisor)); } } if (R) R[0] = remainder; } else { // Now we're ready to invoke the Knuth classical divide algorithm. In this // case n > 1. KnuthDiv(U, V, Q, R, m, n); } // If the caller wants the quotient if (Quotient) { // Set up the Quotient value's memory. if (Quotient->BitWidth != LHS.BitWidth) { if (Quotient->isSingleWord()) Quotient->VAL = 0; else delete [] Quotient->pVal; Quotient->BitWidth = LHS.BitWidth; if (!Quotient->isSingleWord()) Quotient->pVal = getClearedMemory(Quotient->getNumWords()); } else Quotient->clearAllBits(); // The quotient is in Q. Reconstitute the quotient into Quotient's low // order words. if (lhsWords == 1) { uint64_t tmp = uint64_t(Q[0]) | (uint64_t(Q[1]) << (APINT_BITS_PER_WORD / 2)); if (Quotient->isSingleWord()) Quotient->VAL = tmp; else Quotient->pVal[0] = tmp; } else { assert(!Quotient->isSingleWord() && "Quotient APInt not large enough"); for (unsigned i = 0; i < lhsWords; ++i) Quotient->pVal[i] = uint64_t(Q[i*2]) | (uint64_t(Q[i*2+1]) << (APINT_BITS_PER_WORD / 2)); } } // If the caller wants the remainder if (Remainder) { // Set up the Remainder value's memory. if (Remainder->BitWidth != RHS.BitWidth) { if (Remainder->isSingleWord()) Remainder->VAL = 0; else delete [] Remainder->pVal; Remainder->BitWidth = RHS.BitWidth; if (!Remainder->isSingleWord()) Remainder->pVal = getClearedMemory(Remainder->getNumWords()); } else Remainder->clearAllBits(); // The remainder is in R. Reconstitute the remainder into Remainder's low // order words. if (rhsWords == 1) { uint64_t tmp = uint64_t(R[0]) | (uint64_t(R[1]) << (APINT_BITS_PER_WORD / 2)); if (Remainder->isSingleWord()) Remainder->VAL = tmp; else Remainder->pVal[0] = tmp; } else { assert(!Remainder->isSingleWord() && "Remainder APInt not large enough"); for (unsigned i = 0; i < rhsWords; ++i) Remainder->pVal[i] = uint64_t(R[i*2]) | (uint64_t(R[i*2+1]) << (APINT_BITS_PER_WORD / 2)); } } // Clean up the memory we allocated. if (U != &SPACE[0]) { delete [] U; delete [] V; delete [] Q; delete [] R; } } APInt APInt::udiv(const APInt& RHS) const { assert(BitWidth == RHS.BitWidth && "Bit widths must be the same"); // First, deal with the easy case if (isSingleWord()) { assert(RHS.VAL != 0 && "Divide by zero?"); return APInt(BitWidth, VAL / RHS.VAL); } // Get some facts about the LHS and RHS number of bits and words unsigned rhsBits = RHS.getActiveBits(); unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1); assert(rhsWords && "Divided by zero???"); unsigned lhsBits = this->getActiveBits(); unsigned lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1); // Deal with some degenerate cases if (!lhsWords) // 0 / X ===> 0 return APInt(BitWidth, 0); else if (lhsWords < rhsWords || this->ult(RHS)) { // X / Y ===> 0, iff X < Y return APInt(BitWidth, 0); } else if (*this == RHS) { // X / X ===> 1 return APInt(BitWidth, 1); } else if (lhsWords == 1 && rhsWords == 1) { // All high words are zero, just use native divide return APInt(BitWidth, this->pVal[0] / RHS.pVal[0]); } // We have to compute it the hard way. Invoke the Knuth divide algorithm. APInt Quotient(1,0); // to hold result. divide(*this, lhsWords, RHS, rhsWords, &Quotient, 0); return Quotient; } APInt APInt::urem(const APInt& RHS) const { assert(BitWidth == RHS.BitWidth && "Bit widths must be the same"); if (isSingleWord()) { assert(RHS.VAL != 0 && "Remainder by zero?"); return APInt(BitWidth, VAL % RHS.VAL); } // Get some facts about the LHS unsigned lhsBits = getActiveBits(); unsigned lhsWords = !lhsBits ? 0 : (whichWord(lhsBits - 1) + 1); // Get some facts about the RHS unsigned rhsBits = RHS.getActiveBits(); unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1); assert(rhsWords && "Performing remainder operation by zero ???"); // Check the degenerate cases if (lhsWords == 0) { // 0 % Y ===> 0 return APInt(BitWidth, 0); } else if (lhsWords < rhsWords || this->ult(RHS)) { // X % Y ===> X, iff X < Y return *this; } else if (*this == RHS) { // X % X == 0; return APInt(BitWidth, 0); } else if (lhsWords == 1) { // All high words are zero, just use native remainder return APInt(BitWidth, pVal[0] % RHS.pVal[0]); } // We have to compute it the hard way. Invoke the Knuth divide algorithm. APInt Remainder(1,0); divide(*this, lhsWords, RHS, rhsWords, 0, &Remainder); return Remainder; } void APInt::udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, APInt &Remainder) { // Get some size facts about the dividend and divisor unsigned lhsBits = LHS.getActiveBits(); unsigned lhsWords = !lhsBits ? 0 : (APInt::whichWord(lhsBits - 1) + 1); unsigned rhsBits = RHS.getActiveBits(); unsigned rhsWords = !rhsBits ? 0 : (APInt::whichWord(rhsBits - 1) + 1); // Check the degenerate cases if (lhsWords == 0) { Quotient = 0; // 0 / Y ===> 0 Remainder = 0; // 0 % Y ===> 0 return; } if (lhsWords < rhsWords || LHS.ult(RHS)) { Remainder = LHS; // X % Y ===> X, iff X < Y Quotient = 0; // X / Y ===> 0, iff X < Y return; } if (LHS == RHS) { Quotient = 1; // X / X ===> 1 Remainder = 0; // X % X ===> 0; return; } if (lhsWords == 1 && rhsWords == 1) { // There is only one word to consider so use the native versions. uint64_t lhsValue = LHS.isSingleWord() ? LHS.VAL : LHS.pVal[0]; uint64_t rhsValue = RHS.isSingleWord() ? RHS.VAL : RHS.pVal[0]; Quotient = APInt(LHS.getBitWidth(), lhsValue / rhsValue); Remainder = APInt(LHS.getBitWidth(), lhsValue % rhsValue); return; } // Okay, lets do it the long way divide(LHS, lhsWords, RHS, rhsWords, &Quotient, &Remainder); } APInt APInt::sadd_ov(const APInt &RHS, bool &Overflow) const { APInt Res = *this+RHS; Overflow = isNonNegative() == RHS.isNonNegative() && Res.isNonNegative() != isNonNegative(); return Res; } APInt APInt::uadd_ov(const APInt &RHS, bool &Overflow) const { APInt Res = *this+RHS; Overflow = Res.ult(RHS); return Res; } APInt APInt::ssub_ov(const APInt &RHS, bool &Overflow) const { APInt Res = *this - RHS; Overflow = isNonNegative() != RHS.isNonNegative() && Res.isNonNegative() != isNonNegative(); return Res; } APInt APInt::usub_ov(const APInt &RHS, bool &Overflow) const { APInt Res = *this-RHS; Overflow = Res.ugt(*this); return Res; } APInt APInt::sdiv_ov(const APInt &RHS, bool &Overflow) const { // MININT/-1 --> overflow. Overflow = isMinSignedValue() && RHS.isAllOnesValue(); return sdiv(RHS); } APInt APInt::smul_ov(const APInt &RHS, bool &Overflow) const { APInt Res = *this * RHS; if (*this != 0 && RHS != 0) Overflow = Res.sdiv(RHS) != *this || Res.sdiv(*this) != RHS; else Overflow = false; return Res; } APInt APInt::umul_ov(const APInt &RHS, bool &Overflow) const { APInt Res = *this * RHS; if (*this != 0 && RHS != 0) Overflow = Res.udiv(RHS) != *this || Res.udiv(*this) != RHS; else Overflow = false; return Res; } APInt APInt::sshl_ov(unsigned ShAmt, bool &Overflow) const { Overflow = ShAmt >= getBitWidth(); if (Overflow) ShAmt = getBitWidth()-1; if (isNonNegative()) // Don't allow sign change. Overflow = ShAmt >= countLeadingZeros(); else Overflow = ShAmt >= countLeadingOnes(); return *this << ShAmt; } void APInt::fromString(unsigned numbits, StringRef str, uint8_t radix) { // Check our assumptions here assert(!str.empty() && "Invalid string length"); assert((radix == 10 || radix == 8 || radix == 16 || radix == 2 || radix == 36) && "Radix should be 2, 8, 10, 16, or 36!"); StringRef::iterator p = str.begin(); size_t slen = str.size(); bool isNeg = *p == '-'; if (*p == '-' || *p == '+') { p++; slen--; assert(slen && "String is only a sign, needs a value."); } assert((slen <= numbits || radix != 2) && "Insufficient bit width"); assert(((slen-1)*3 <= numbits || radix != 8) && "Insufficient bit width"); assert(((slen-1)*4 <= numbits || radix != 16) && "Insufficient bit width"); assert((((slen-1)*64)/22 <= numbits || radix != 10) && "Insufficient bit width"); // Allocate memory if (!isSingleWord()) pVal = getClearedMemory(getNumWords()); // Figure out if we can shift instead of multiply unsigned shift = (radix == 16 ? 4 : radix == 8 ? 3 : radix == 2 ? 1 : 0); // Set up an APInt for the digit to add outside the loop so we don't // constantly construct/destruct it. APInt apdigit(getBitWidth(), 0); APInt apradix(getBitWidth(), radix); // Enter digit traversal loop for (StringRef::iterator e = str.end(); p != e; ++p) { unsigned digit = getDigit(*p, radix); assert(digit < radix && "Invalid character in digit string"); // Shift or multiply the value by the radix if (slen > 1) { if (shift) *this <<= shift; else *this *= apradix; } // Add in the digit we just interpreted if (apdigit.isSingleWord()) apdigit.VAL = digit; else apdigit.pVal[0] = digit; *this += apdigit; } // If its negative, put it in two's complement form if (isNeg) { (*this)--; this->flipAllBits(); } } void APInt::toString(SmallVectorImpl<char> &Str, unsigned Radix, bool Signed, bool formatAsCLiteral) const { assert((Radix == 10 || Radix == 8 || Radix == 16 || Radix == 2 || Radix == 36) && "Radix should be 2, 8, 10, or 16!"); const char *Prefix = ""; if (formatAsCLiteral) { switch (Radix) { case 2: // Binary literals are a non-standard extension added in gcc 4.3: // http://gcc.gnu.org/onlinedocs/gcc-4.3.0/gcc/Binary-constants.html Prefix = "0b"; break; case 8: Prefix = "0"; break; case 16: Prefix = "0x"; break; } } // First, check for a zero value and just short circuit the logic below. if (*this == 0) { while (*Prefix) { Str.push_back(*Prefix); ++Prefix; }; Str.push_back('0'); return; } static const char Digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; if (isSingleWord()) { char Buffer[65]; char *BufPtr = Buffer+65; uint64_t N; if (!Signed) { N = getZExtValue(); } else { int64_t I = getSExtValue(); if (I >= 0) { N = I; } else { Str.push_back('-'); N = -(uint64_t)I; } } while (*Prefix) { Str.push_back(*Prefix); ++Prefix; }; while (N) { *--BufPtr = Digits[N % Radix]; N /= Radix; } Str.append(BufPtr, Buffer+65); return; } APInt Tmp(*this); if (Signed && isNegative()) { // They want to print the signed version and it is a negative value // Flip the bits and add one to turn it into the equivalent positive // value and put a '-' in the result. Tmp.flipAllBits(); Tmp++; Str.push_back('-'); } while (*Prefix) { Str.push_back(*Prefix); ++Prefix; }; // We insert the digits backward, then reverse them to get the right order. unsigned StartDig = Str.size(); // For the 2, 8 and 16 bit cases, we can just shift instead of divide // because the number of bits per digit (1, 3 and 4 respectively) divides // equaly. We just shift until the value is zero. if (Radix == 2 || Radix == 8 || Radix == 16) { // Just shift tmp right for each digit width until it becomes zero unsigned ShiftAmt = (Radix == 16 ? 4 : (Radix == 8 ? 3 : 1)); unsigned MaskAmt = Radix - 1; while (Tmp != 0) { unsigned Digit = unsigned(Tmp.getRawData()[0]) & MaskAmt; Str.push_back(Digits[Digit]); Tmp = Tmp.lshr(ShiftAmt); } } else { APInt divisor(Radix == 10? 4 : 8, Radix); while (Tmp != 0) { APInt APdigit(1, 0); APInt tmp2(Tmp.getBitWidth(), 0); divide(Tmp, Tmp.getNumWords(), divisor, divisor.getNumWords(), &tmp2, &APdigit); unsigned Digit = (unsigned)APdigit.getZExtValue(); assert(Digit < Radix && "divide failed"); Str.push_back(Digits[Digit]); Tmp = tmp2; } } // Reverse the digits before returning. std::reverse(Str.begin()+StartDig, Str.end()); } /// toString - This returns the APInt as a std::string. Note that this is an /// inefficient method. It is better to pass in a SmallVector/SmallString /// to the methods above. std::string APInt::toString(unsigned Radix = 10, bool Signed = true) const { SmallString<40> S; toString(S, Radix, Signed, /* formatAsCLiteral = */false); return S.str(); } void APInt::dump() const { SmallString<40> S, U; this->toStringUnsigned(U); this->toStringSigned(S); std::cerr << "APInt(" << BitWidth << "b, " << U.str().str() << "u " << S.str().str() << "s)"; } void APInt::print(std::ostream &OS, bool isSigned) const { SmallString<40> S; this->toString(S, 10, isSigned, /* formatAsCLiteral = */false); OS << S.str().str(); } // This implements a variety of operations on a representation of // arbitrary precision, two's-complement, bignum integer values. // Assumed by lowHalf, highHalf, partMSB and partLSB. A fairly safe // and unrestricting assumption. #define COMPILE_TIME_ASSERT(cond) extern int CTAssert[(cond) ? 1 : -1] COMPILE_TIME_ASSERT(integerPartWidth % 2 == 0); /* Some handy functions local to this file. */ namespace { /* Returns the integer part with the least significant BITS set. BITS cannot be zero. */ static inline integerPart lowBitMask(unsigned int bits) { assert(bits != 0 && bits <= integerPartWidth); return ~(integerPart) 0 >> (integerPartWidth - bits); } /* Returns the value of the lower half of PART. */ static inline integerPart lowHalf(integerPart part) { return part & lowBitMask(integerPartWidth / 2); } /* Returns the value of the upper half of PART. */ static inline integerPart highHalf(integerPart part) { return part >> (integerPartWidth / 2); } /* Returns the bit number of the most significant set bit of a part. If the input number has no bits set -1U is returned. */ static unsigned int partMSB(integerPart value) { unsigned int n, msb; if (value == 0) return -1U; n = integerPartWidth / 2; msb = 0; do { if (value >> n) { value >>= n; msb += n; } n >>= 1; } while (n); return msb; } /* Returns the bit number of the least significant set bit of a part. If the input number has no bits set -1U is returned. */ static unsigned int partLSB(integerPart value) { unsigned int n, lsb; if (value == 0) return -1U; lsb = integerPartWidth - 1; n = integerPartWidth / 2; do { if (value << n) { value <<= n; lsb -= n; } n >>= 1; } while (n); return lsb; } } /* Sets the least significant part of a bignum to the input value, and zeroes out higher parts. */ void APInt::tcSet(integerPart *dst, integerPart part, unsigned int parts) { unsigned int i; assert(parts > 0); dst[0] = part; for (i = 1; i < parts; i++) dst[i] = 0; } /* Assign one bignum to another. */ void APInt::tcAssign(integerPart *dst, const integerPart *src, unsigned int parts) { unsigned int i; for (i = 0; i < parts; i++) dst[i] = src[i]; } /* Returns true if a bignum is zero, false otherwise. */ bool APInt::tcIsZero(const integerPart *src, unsigned int parts) { unsigned int i; for (i = 0; i < parts; i++) if (src[i]) return false; return true; } /* Extract the given bit of a bignum; returns 0 or 1. */ int APInt::tcExtractBit(const integerPart *parts, unsigned int bit) { return (parts[bit / integerPartWidth] & ((integerPart) 1 << bit % integerPartWidth)) != 0; } /* Set the given bit of a bignum. */ void APInt::tcSetBit(integerPart *parts, unsigned int bit) { parts[bit / integerPartWidth] |= (integerPart) 1 << (bit % integerPartWidth); } /* Clears the given bit of a bignum. */ void APInt::tcClearBit(integerPart *parts, unsigned int bit) { parts[bit / integerPartWidth] &= ~((integerPart) 1 << (bit % integerPartWidth)); } /* Returns the bit number of the least significant set bit of a number. If the input number has no bits set -1U is returned. */ unsigned int APInt::tcLSB(const integerPart *parts, unsigned int n) { unsigned int i, lsb; for (i = 0; i < n; i++) { if (parts[i] != 0) { lsb = partLSB(parts[i]); return lsb + i * integerPartWidth; } } return -1U; } /* Returns the bit number of the most significant set bit of a number. If the input number has no bits set -1U is returned. */ unsigned int APInt::tcMSB(const integerPart *parts, unsigned int n) { unsigned int msb; do { --n; if (parts[n] != 0) { msb = partMSB(parts[n]); return msb + n * integerPartWidth; } } while (n); return -1U; } /* Copy the bit vector of width srcBITS from SRC, starting at bit srcLSB, to DST, of dstCOUNT parts, such that the bit srcLSB becomes the least significant bit of DST. All high bits above srcBITS in DST are zero-filled. */ void APInt::tcExtract(integerPart *dst, unsigned int dstCount,const integerPart *src, unsigned int srcBits, unsigned int srcLSB) { unsigned int firstSrcPart, dstParts, shift, n; dstParts = (srcBits + integerPartWidth - 1) / integerPartWidth; assert(dstParts <= dstCount); firstSrcPart = srcLSB / integerPartWidth; tcAssign (dst, src + firstSrcPart, dstParts); shift = srcLSB % integerPartWidth; tcShiftRight (dst, dstParts, shift); /* We now have (dstParts * integerPartWidth - shift) bits from SRC in DST. If this is less that srcBits, append the rest, else clear the high bits. */ n = dstParts * integerPartWidth - shift; if (n < srcBits) { integerPart mask = lowBitMask (srcBits - n); dst[dstParts - 1] |= ((src[firstSrcPart + dstParts] & mask) << n % integerPartWidth); } else if (n > srcBits) { if (srcBits % integerPartWidth) dst[dstParts - 1] &= lowBitMask (srcBits % integerPartWidth); } /* Clear high parts. */ while (dstParts < dstCount) dst[dstParts++] = 0; } /* DST += RHS + C where C is zero or one. Returns the carry flag. */ integerPart APInt::tcAdd(integerPart *dst, const integerPart *rhs, integerPart c, unsigned int parts) { unsigned int i; assert(c <= 1); for (i = 0; i < parts; i++) { integerPart l; l = dst[i]; if (c) { dst[i] += rhs[i] + 1; c = (dst[i] <= l); } else { dst[i] += rhs[i]; c = (dst[i] < l); } } return c; } /* DST -= RHS + C where C is zero or one. Returns the carry flag. */ integerPart APInt::tcSubtract(integerPart *dst, const integerPart *rhs, integerPart c, unsigned int parts) { unsigned int i; assert(c <= 1); for (i = 0; i < parts; i++) { integerPart l; l = dst[i]; if (c) { dst[i] -= rhs[i] + 1; c = (dst[i] >= l); } else { dst[i] -= rhs[i]; c = (dst[i] > l); } } return c; } /* Negate a bignum in-place. */ void APInt::tcNegate(integerPart *dst, unsigned int parts) { tcComplement(dst, parts); tcIncrement(dst, parts); } /* DST += SRC * MULTIPLIER + CARRY if add is true DST = SRC * MULTIPLIER + CARRY if add is false Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC they must start at the same point, i.e. DST == SRC. If DSTPARTS == SRCPARTS + 1 no overflow occurs and zero is returned. Otherwise DST is filled with the least significant DSTPARTS parts of the result, and if all of the omitted higher parts were zero return zero, otherwise overflow occurred and return one. */ int APInt::tcMultiplyPart(integerPart *dst, const integerPart *src, integerPart multiplier, integerPart carry, unsigned int srcParts, unsigned int dstParts, bool add) { unsigned int i, n; /* Otherwise our writes of DST kill our later reads of SRC. */ assert(dst <= src || dst >= src + srcParts); assert(dstParts <= srcParts + 1); /* N loops; minimum of dstParts and srcParts. */ n = dstParts < srcParts ? dstParts: srcParts; for (i = 0; i < n; i++) { integerPart low, mid, high, srcPart; /* [ LOW, HIGH ] = MULTIPLIER * SRC[i] + DST[i] + CARRY. This cannot overflow, because (n - 1) * (n - 1) + 2 (n - 1) = (n - 1) * (n + 1) which is less than n^2. */ srcPart = src[i]; if (multiplier == 0 || srcPart == 0) { low = carry; high = 0; } else { low = lowHalf(srcPart) * lowHalf(multiplier); high = highHalf(srcPart) * highHalf(multiplier); mid = lowHalf(srcPart) * highHalf(multiplier); high += highHalf(mid); mid <<= integerPartWidth / 2; if (low + mid < low) high++; low += mid; mid = highHalf(srcPart) * lowHalf(multiplier); high += highHalf(mid); mid <<= integerPartWidth / 2; if (low + mid < low) high++; low += mid; /* Now add carry. */ if (low + carry < low) high++; low += carry; } if (add) { /* And now DST[i], and store the new low part there. */ if (low + dst[i] < low) high++; dst[i] += low; } else dst[i] = low; carry = high; } if (i < dstParts) { /* Full multiplication, there is no overflow. */ assert(i + 1 == dstParts); dst[i] = carry; return 0; } else { /* We overflowed if there is carry. */ if (carry) return 1; /* We would overflow if any significant unwritten parts would be non-zero. This is true if any remaining src parts are non-zero and the multiplier is non-zero. */ if (multiplier) for (; i < srcParts; i++) if (src[i]) return 1; /* We fitted in the narrow destination. */ return 0; } } /* DST = LHS * RHS, where DST has the same width as the operands and is filled with the least significant parts of the result. Returns one if overflow occurred, otherwise zero. DST must be disjoint from both operands. */ int APInt::tcMultiply(integerPart *dst, const integerPart *lhs, const integerPart *rhs, unsigned int parts) { unsigned int i; int overflow; assert(dst != lhs && dst != rhs); overflow = 0; tcSet(dst, 0, parts); for (i = 0; i < parts; i++) overflow |= tcMultiplyPart(&dst[i], lhs, rhs[i], 0, parts, parts - i, true); return overflow; } /* DST = LHS * RHS, where DST has width the sum of the widths of the operands. No overflow occurs. DST must be disjoint from both operands. Returns the number of parts required to hold the result. */ unsigned int APInt::tcFullMultiply(integerPart *dst, const integerPart *lhs, const integerPart *rhs, unsigned int lhsParts, unsigned int rhsParts) { /* Put the narrower number on the LHS for less loops below. */ if (lhsParts > rhsParts) { return tcFullMultiply (dst, rhs, lhs, rhsParts, lhsParts); } else { unsigned int n; assert(dst != lhs && dst != rhs); tcSet(dst, 0, rhsParts); for (n = 0; n < lhsParts; n++) tcMultiplyPart(&dst[n], rhs, lhs[n], 0, rhsParts, rhsParts + 1, true); n = lhsParts + rhsParts; return n - (dst[n - 1] == 0); } } /* If RHS is zero LHS and REMAINDER are left unchanged, return one. Otherwise set LHS to LHS / RHS with the fractional part discarded, set REMAINDER to the remainder, return zero. i.e. OLD_LHS = RHS * LHS + REMAINDER SCRATCH is a bignum of the same size as the operands and result for use by the routine; its contents need not be initialized and are destroyed. LHS, REMAINDER and SCRATCH must be distinct. */ int APInt::tcDivide(integerPart *lhs, const integerPart *rhs, integerPart *remainder, integerPart *srhs, unsigned int parts) { unsigned int n, shiftCount; integerPart mask; assert(lhs != remainder && lhs != srhs && remainder != srhs); shiftCount = tcMSB(rhs, parts) + 1; if (shiftCount == 0) return true; shiftCount = parts * integerPartWidth - shiftCount; n = shiftCount / integerPartWidth; mask = (integerPart) 1 << (shiftCount % integerPartWidth); tcAssign(srhs, rhs, parts); tcShiftLeft(srhs, parts, shiftCount); tcAssign(remainder, lhs, parts); tcSet(lhs, 0, parts); /* Loop, subtracting SRHS if REMAINDER is greater and adding that to the total. */ for (;;) { int compare; compare = tcCompare(remainder, srhs, parts); if (compare >= 0) { tcSubtract(remainder, srhs, 0, parts); lhs[n] |= mask; } if (shiftCount == 0) break; shiftCount--; tcShiftRight(srhs, parts, 1); if ((mask >>= 1) == 0) mask = (integerPart) 1 << (integerPartWidth - 1), n--; } return false; } /* Shift a bignum left COUNT bits in-place. Shifted in bits are zero. There are no restrictions on COUNT. */ void APInt::tcShiftLeft(integerPart *dst, unsigned int parts, unsigned int count) { if (count) { unsigned int jump, shift; /* Jump is the inter-part jump; shift is is intra-part shift. */ jump = count / integerPartWidth; shift = count % integerPartWidth; while (parts > jump) { integerPart part; parts--; /* dst[i] comes from the two parts src[i - jump] and, if we have an intra-part shift, src[i - jump - 1]. */ part = dst[parts - jump]; if (shift) { part <<= shift; if (parts >= jump + 1) part |= dst[parts - jump - 1] >> (integerPartWidth - shift); } dst[parts] = part; } while (parts > 0) dst[--parts] = 0; } } /* Shift a bignum right COUNT bits in-place. Shifted in bits are zero. There are no restrictions on COUNT. */ void APInt::tcShiftRight(integerPart *dst, unsigned int parts, unsigned int count) { if (count) { unsigned int i, jump, shift; /* Jump is the inter-part jump; shift is is intra-part shift. */ jump = count / integerPartWidth; shift = count % integerPartWidth; /* Perform the shift. This leaves the most significant COUNT bits of the result at zero. */ for (i = 0; i < parts; i++) { integerPart part; if (i + jump >= parts) { part = 0; } else { part = dst[i + jump]; if (shift) { part >>= shift; if (i + jump + 1 < parts) part |= dst[i + jump + 1] << (integerPartWidth - shift); } } dst[i] = part; } } } /* Bitwise and of two bignums. */ void APInt::tcAnd(integerPart *dst, const integerPart *rhs, unsigned int parts) { unsigned int i; for (i = 0; i < parts; i++) dst[i] &= rhs[i]; } /* Bitwise inclusive or of two bignums. */ void APInt::tcOr(integerPart *dst, const integerPart *rhs, unsigned int parts) { unsigned int i; for (i = 0; i < parts; i++) dst[i] |= rhs[i]; } /* Bitwise exclusive or of two bignums. */ void APInt::tcXor(integerPart *dst, const integerPart *rhs, unsigned int parts) { unsigned int i; for (i = 0; i < parts; i++) dst[i] ^= rhs[i]; } /* Complement a bignum in-place. */ void APInt::tcComplement(integerPart *dst, unsigned int parts) { unsigned int i; for (i = 0; i < parts; i++) dst[i] = ~dst[i]; } /* Comparison (unsigned) of two bignums. */ int APInt::tcCompare(const integerPart *lhs, const integerPart *rhs, unsigned int parts) { while (parts) { parts--; if (lhs[parts] == rhs[parts]) continue; if (lhs[parts] > rhs[parts]) return 1; else return -1; } return 0; } /* Increment a bignum in-place, return the carry flag. */ integerPart APInt::tcIncrement(integerPart *dst, unsigned int parts) { unsigned int i; for (i = 0; i < parts; i++) if (++dst[i] != 0) break; return i == parts; } /* Set the least significant BITS bits of a bignum, clear the rest. */ void APInt::tcSetLeastSignificantBits(integerPart *dst, unsigned int parts, unsigned int bits) { unsigned int i; i = 0; while (bits > integerPartWidth) { dst[i++] = ~(integerPart) 0; bits -= integerPartWidth; } if (bits) dst[i++] = ~(integerPart) 0 >> (integerPartWidth - bits); while (i < parts) dst[i++] = 0; }
0
rapidsai_public_repos/code-share/maxflow/galois/src
rapidsai_public_repos/code-share/maxflow/galois/src/llvm/StringMap.cpp
//===--- StringMap.cpp - String Hash table map implementation -------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the StringMap class. // //===----------------------------------------------------------------------===// #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringExtras.h" #include <cassert> using namespace llvm; StringMapImpl::StringMapImpl(unsigned InitSize, unsigned itemSize) { ItemSize = itemSize; // If a size is specified, initialize the table with that many buckets. if (InitSize) { init(InitSize); return; } // Otherwise, initialize it with zero buckets to avoid the allocation. TheTable = 0; NumBuckets = 0; NumItems = 0; NumTombstones = 0; } void StringMapImpl::init(unsigned InitSize) { assert((InitSize & (InitSize-1)) == 0 && "Init Size must be a power of 2 or zero!"); NumBuckets = InitSize ? InitSize : 16; NumItems = 0; NumTombstones = 0; TheTable = (ItemBucket*)calloc(NumBuckets+1, sizeof(ItemBucket)); // Allocate one extra bucket, set it to look filled so the iterators stop at // end. TheTable[NumBuckets].Item = (StringMapEntryBase*)2; } /// LookupBucketFor - Look up the bucket that the specified string should end /// up in. If it already exists as a key in the map, the Item pointer for the /// specified bucket will be non-null. Otherwise, it will be null. In either /// case, the FullHashValue field of the bucket will be set to the hash value /// of the string. unsigned StringMapImpl::LookupBucketFor(StringRef Name) { unsigned HTSize = NumBuckets; if (HTSize == 0) { // Hash table unallocated so far? init(16); HTSize = NumBuckets; } unsigned FullHashValue = HashString(Name); unsigned BucketNo = FullHashValue & (HTSize-1); unsigned ProbeAmt = 1; int FirstTombstone = -1; while (1) { ItemBucket &Bucket = TheTable[BucketNo]; StringMapEntryBase *BucketItem = Bucket.Item; // If we found an empty bucket, this key isn't in the table yet, return it. if (BucketItem == 0) { // If we found a tombstone, we want to reuse the tombstone instead of an // empty bucket. This reduces probing. if (FirstTombstone != -1) { TheTable[FirstTombstone].FullHashValue = FullHashValue; return FirstTombstone; } Bucket.FullHashValue = FullHashValue; return BucketNo; } if (BucketItem == getTombstoneVal()) { // Skip over tombstones. However, remember the first one we see. if (FirstTombstone == -1) FirstTombstone = BucketNo; } else if (Bucket.FullHashValue == FullHashValue) { // If the full hash value matches, check deeply for a match. The common // case here is that we are only looking at the buckets (for item info // being non-null and for the full hash value) not at the items. This // is important for cache locality. // Do the comparison like this because Name isn't necessarily // null-terminated! char *ItemStr = (char*)BucketItem+ItemSize; if (Name == StringRef(ItemStr, BucketItem->getKeyLength())) { // We found a match! return BucketNo; } } // Okay, we didn't find the item. Probe to the next bucket. BucketNo = (BucketNo+ProbeAmt) & (HTSize-1); // Use quadratic probing, it has fewer clumping artifacts than linear // probing and has good cache behavior in the common case. ++ProbeAmt; } } /// FindKey - Look up the bucket that contains the specified key. If it exists /// in the map, return the bucket number of the key. Otherwise return -1. /// This does not modify the map. int StringMapImpl::FindKey(StringRef Key) const { unsigned HTSize = NumBuckets; if (HTSize == 0) return -1; // Really empty table? unsigned FullHashValue = HashString(Key); unsigned BucketNo = FullHashValue & (HTSize-1); unsigned ProbeAmt = 1; while (1) { ItemBucket &Bucket = TheTable[BucketNo]; StringMapEntryBase *BucketItem = Bucket.Item; // If we found an empty bucket, this key isn't in the table yet, return. if (BucketItem == 0) return -1; if (BucketItem == getTombstoneVal()) { // Ignore tombstones. } else if (Bucket.FullHashValue == FullHashValue) { // If the full hash value matches, check deeply for a match. The common // case here is that we are only looking at the buckets (for item info // being non-null and for the full hash value) not at the items. This // is important for cache locality. // Do the comparison like this because NameStart isn't necessarily // null-terminated! char *ItemStr = (char*)BucketItem+ItemSize; if (Key == StringRef(ItemStr, BucketItem->getKeyLength())) { // We found a match! return BucketNo; } } // Okay, we didn't find the item. Probe to the next bucket. BucketNo = (BucketNo+ProbeAmt) & (HTSize-1); // Use quadratic probing, it has fewer clumping artifacts than linear // probing and has good cache behavior in the common case. ++ProbeAmt; } } /// RemoveKey - Remove the specified StringMapEntry from the table, but do not /// delete it. This aborts if the value isn't in the table. void StringMapImpl::RemoveKey(StringMapEntryBase *V) { const char *VStr = (char*)V + ItemSize; StringMapEntryBase *V2 = RemoveKey(StringRef(VStr, V->getKeyLength())); (void)V2; assert(V == V2 && "Didn't find key?"); } /// RemoveKey - Remove the StringMapEntry for the specified key from the /// table, returning it. If the key is not in the table, this returns null. StringMapEntryBase *StringMapImpl::RemoveKey(StringRef Key) { int Bucket = FindKey(Key); if (Bucket == -1) return 0; StringMapEntryBase *Result = TheTable[Bucket].Item; TheTable[Bucket].Item = getTombstoneVal(); --NumItems; ++NumTombstones; assert(NumItems + NumTombstones <= NumBuckets); return Result; } /// RehashTable - Grow the table, redistributing values into the buckets with /// the appropriate mod-of-hashtable-size. void StringMapImpl::RehashTable() { unsigned NewSize; // If the hash table is now more than 3/4 full, or if fewer than 1/8 of // the buckets are empty (meaning that many are filled with tombstones), // grow/rehash the table. if (NumItems*4 > NumBuckets*3) { NewSize = NumBuckets*2; } else if (NumBuckets-(NumItems+NumTombstones) < NumBuckets/8) { NewSize = NumBuckets; } else { return; } // Allocate one extra bucket which will always be non-empty. This allows the // iterators to stop at end. ItemBucket *NewTableArray =(ItemBucket*)calloc(NewSize+1, sizeof(ItemBucket)); NewTableArray[NewSize].Item = (StringMapEntryBase*)2; // Rehash all the items into their new buckets. Luckily :) we already have // the hash values available, so we don't have to rehash any strings. for (ItemBucket *IB = TheTable, *E = TheTable+NumBuckets; IB != E; ++IB) { if (IB->Item && IB->Item != getTombstoneVal()) { // Fast case, bucket available. unsigned FullHash = IB->FullHashValue; unsigned NewBucket = FullHash & (NewSize-1); if (NewTableArray[NewBucket].Item == 0) { NewTableArray[FullHash & (NewSize-1)].Item = IB->Item; NewTableArray[FullHash & (NewSize-1)].FullHashValue = FullHash; continue; } // Otherwise probe for a spot. unsigned ProbeSize = 1; do { NewBucket = (NewBucket + ProbeSize++) & (NewSize-1); } while (NewTableArray[NewBucket].Item); // Finally found a slot. Fill it in. NewTableArray[NewBucket].Item = IB->Item; NewTableArray[NewBucket].FullHashValue = FullHash; } } free(TheTable); TheTable = NewTableArray; NumBuckets = NewSize; NumTombstones = 0; }
0
rapidsai_public_repos/code-share/maxflow/galois/src
rapidsai_public_repos/code-share/maxflow/galois/src/mm-nonuma/CMakeLists.txt
add_definitions(-DGALOIS_FORCE_NO_NUMA) add_internal_library(mm-nonuma ../mm/Mem.cpp ../mm/NumaMem.cpp ../mm/PageAlloc.cpp)
0
rapidsai_public_repos/code-share/maxflow/galois
rapidsai_public_repos/code-share/maxflow/galois/apps/CMakeLists.txt
if(NOT CMAKE_CXX_COMPILER_ID MATCHES "XL") add_subdirectory(avi) add_subdirectory(connectedcomponents) add_subdirectory(des) add_subdirectory(kruskal) add_subdirectory(gmetis) endif() add_subdirectory(barneshut) add_subdirectory(betweennesscentrality) add_subdirectory(bfs) add_subdirectory(boruvka) add_subdirectory(clustering) add_subdirectory(delaunayrefinement) add_subdirectory(delaunaytriangulation) add_subdirectory(independentset) add_subdirectory(matching) add_subdirectory(pagerank) add_subdirectory(pta) add_subdirectory(preflowpush) add_subdirectory(sssp) add_subdirectory(surveypropagation) add_subdirectory(spanningtree) add_subdirectory(tutorial)
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/delaunaytriangulation/Element.h
/** An element (i.e., a triangle or a boundary line) -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2012, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author Xin Sui <[email protected]> * @author Donald Nguyen <[email protected]> */ #ifndef ELEMENT_H #define ELEMENT_H #include "Tuple.h" #include <ostream> #include <stdlib.h> class Point; class Element { Point* points[3]; public: Element(const Element& e) { points[0] = e.points[0]; points[1] = e.points[1]; points[2] = e.points[2]; } Element(Point* a, Point* b, Point* c) { points[0] = a; points[1] = b; points[2] = c; } Element(Point* a, Point* b) { points[0] = a; points[1] = b; points[2] = NULL; } Point* getPoint(int i) { return points[i]; } const Point* getPoint(int i) const { return points[i]; } bool boundary() const { return points[2] == NULL; } int dim() const { return boundary() ? 2 : 3; } bool clockwise() const; //! determine if a tuple is inside the triangle bool inTriangle(const Tuple& p) const; //! determine if the circumcircle of the triangle contains the tuple bool inCircle(const Tuple& p) const; std::ostream& print(std::ostream& out) const; }; std::ostream& operator<<(std::ostream& out, const Element& e); #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/delaunaytriangulation/Tuple.h
/** A tuple -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author Xin Sui <[email protected]> */ #ifndef TUPLE_H #define TUPLE_H #include <ostream> #include <cmath> typedef double TupleDataTy; class Tuple { TupleDataTy data[2]; public: Tuple() { data[0] = 0; data[1] = 0; } Tuple(TupleDataTy xy) { data[0] = xy; data[1] = xy; } Tuple(TupleDataTy x, TupleDataTy y) { data[0] = x; data[1] = y; } int dim() const { return 2; } TupleDataTy x() const { return data[0]; } TupleDataTy y() const { return data[1]; } TupleDataTy& x() { return data[0]; } TupleDataTy& y() { return data[1]; } bool operator==(const Tuple& rhs) const { for (int i = 0; i < 2; ++i) { if (data[i] != rhs.data[i]) return false; } return true; } bool operator!=(const Tuple& rhs) const { return !(*this == rhs); } TupleDataTy operator[](int index) const { return data[index]; } TupleDataTy& operator[](int index) { return data[index]; } Tuple operator+(const Tuple& rhs) const { return Tuple(data[0]+rhs.data[0], data[1]+rhs.data[1]); } Tuple operator-(const Tuple& rhs) const { return Tuple(data[0]-rhs.data[0], data[1]-rhs.data[1]); } //!scalar product Tuple operator*(TupleDataTy d) const { return Tuple(data[0]*d, data[1]*d); } //! dot product TupleDataTy dot(const Tuple& rhs) const { return data[0]*rhs.data[0] + data[1]*rhs.data[1]; } TupleDataTy cross(const Tuple& rhs) const { return data[0]*rhs.data[1] - data[1]*rhs.data[0]; } void print(std::ostream& os) const { os << "(" << data[0] << ", " << data[1] << ")"; } }; static inline std::ostream& operator<<(std::ostream& os, const Tuple& rhs) { rhs.print(os); return os; } class Tuple3 { TupleDataTy data[3]; public: Tuple3() { data[0] = 0; data[1] = 0; data[2] = 0;} Tuple3(TupleDataTy xyz) { data[0] = xyz; data[1] = xyz; data[1] = xyz;} Tuple3(TupleDataTy x, TupleDataTy y, TupleDataTy z) { data[0] = x; data[1] = y; data[2] = z;} int dim() const { return 3; } TupleDataTy x() const { return data[0]; } TupleDataTy y() const { return data[1]; } TupleDataTy z() const { return data[2]; } TupleDataTy& x() { return data[0]; } TupleDataTy& y() { return data[1]; } TupleDataTy& z() { return data[2]; } bool operator==(const Tuple3& rhs) const { for (int i = 0; i < 3; ++i) { if (data[i] != rhs.data[i]) return false; } return true; } bool operator!=(const Tuple3& rhs) const { return !(*this == rhs); } TupleDataTy operator[](int index) const { return data[index]; } TupleDataTy& operator[](int index) { return data[index]; } Tuple3 operator+(const Tuple3& rhs) const { return Tuple3(data[0]+rhs.data[0], data[1]+rhs.data[1], data[2]+rhs.data[2]); } Tuple3 operator-(const Tuple3& rhs) const { return Tuple3(data[0]-rhs.data[0], data[1]-rhs.data[1], data[2]+rhs.data[2]); } //!scalar product Tuple3 operator*(TupleDataTy d) const { return Tuple3(data[0]*d, data[1]*d, data[2]*d); } //! dot product TupleDataTy dot(const Tuple3& rhs) const { return data[0]*rhs.data[0] + data[1]*rhs.data[1] + data[2]*rhs.data[2]; } Tuple3 cross(const Tuple3& rhs) const { return Tuple3(data[1]*rhs.data[2] - data[2]*rhs.data[1], data[2]*rhs.data[0] - data[0]*rhs.data[2], data[0]*rhs.data[1] - data[1]*rhs.data[0]); } void print(std::ostream& os) const { os << "(" << data[0] << ", " << data[1] << ", " << data[2] << ")"; } }; static inline std::ostream& operator<<(std::ostream& os, const Tuple3& rhs) { rhs.print(os); return os; } #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/delaunaytriangulation/Verifier.h
/** Delaunay triangulation verifier -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2012, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @section Description * * @author Xin Sui <[email protected]> */ #ifndef VERIFIER_H #define VERIFIER_H #include "Graph.h" #include "Point.h" #include "Galois/Galois.h" #include "Galois/ParallelSTL/ParallelSTL.h" #include <stack> #include <set> #include <iostream> class Verifier { struct inconsistent: public std::unary_function<GNode,bool> { Graph* graph; inconsistent(Graph* g): graph(g) { } bool operator()(const GNode& node) const { Element& e = graph->getData(node); size_t dist = std::distance(graph->edge_begin(node), graph->edge_end(node)); if (e.dim() == 2) { if (dist != 1) { std::cerr << "Error: Segment " << e << " has " << dist << " relation(s)\n"; return true; } } else if (e.dim() == 3) { if (dist != 3) { std::cerr << "Error: Triangle " << e << " has " << dist << " relation(s)\n"; return true; } } else { std::cerr << "Error: Element with " << e.dim() << " edges\n"; return true; } return false; } }; struct not_delaunay: public std::unary_function<GNode,bool> { Graph* graph; not_delaunay(Graph* g): graph(g) { } bool operator()(const GNode& node) { Element& e1 = graph->getData(node); for (Graph::edge_iterator jj = graph->edge_begin(node), ej = graph->edge_end(node); jj != ej; ++jj) { const GNode& n = graph->getEdgeDst(jj); Element& e2 = graph->getData(n); if (e1.dim() == 3 && e2.dim() == 3) { Tuple t2; if (!getTupleT2OfRelatedEdge(e1, e2, t2)) { std::cerr << "missing tuple\n"; return true; } if (e1.inCircle(t2)) { std::cerr << "Delaunay property violated: point " << t2 << " in element " << e1 << "\n"; return true; } } } return false; } bool getTupleT2OfRelatedEdge(const Element& e1, const Element& e2, Tuple& t) { int e2_0 = -1; int e2_1 = -1; int phase = 0; for (int i = 0; i < e1.dim(); i++) { for (int j = 0; j < e2.dim(); j++) { if (e1.getPoint(i) != e2.getPoint(j)) continue; if (phase == 0) { e2_0 = j; phase = 1; break; } e2_1 = j; for (int k = 0; k < 3; k++) { if (k != e2_0 && k != e2_1) { t = e2.getPoint(k)->t(); return true; } } } } return false; } }; bool checkReachability(Graph* graph) { std::stack<GNode> remaining; std::set<GNode> found; remaining.push(*(graph->begin())); while (!remaining.empty()) { GNode node = remaining.top(); remaining.pop(); if (!found.count(node)) { if (!graph->containsNode(node)) { std::cerr << "Reachable node was removed from graph\n"; } found.insert(node); int i = 0; for (Graph::edge_iterator ii = graph->edge_begin(node), ei = graph->edge_end(node); ii != ei; ++ii) { GNode n = graph->getEdgeDst(ii); assert(i < 3); assert(graph->containsNode(n)); assert(node != n); ++i; remaining.push(n); } } } if (found.size() != graph->size()) { std::cerr << "Error: Not all elements are reachable. "; std::cerr << "Found: " << found.size() << " needed: " << graph->size() << ".\n"; return false; } return true; } public: bool verify(Graph* g) { return Galois::ParallelSTL::find_if(g->begin(), g->end(), inconsistent(g)) == g->end() && Galois::ParallelSTL::find_if(g->begin(), g->end(), not_delaunay(g)) == g->end() && checkReachability(g); } }; #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/delaunaytriangulation/CMakeLists.txt
#if(CMAKE_CXX_COMPILER_ID MATCHES "Intel") # message(WARNING "NOT compiling delaunaytriangulation (compiler error in ICPC 12.1.0 20111011)") #else() #endif() if(CMAKE_COMPILER_IS_GNUCC) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -ffast-math") endif() app(delaunaytriangulation DelaunayTriangulation.cpp Element.cpp) app(delaunaytriangulation-det DelaunayTriangulationDet.cpp Element.cpp)
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/delaunaytriangulation/Point.h
/** A coordinate and possibly a link to a containing triangle -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2012, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author Xin Sui <[email protected]> * @author Donald Nguyen <[email protected]> */ #ifndef POINT_H #define POINT_H #include "Tuple.h" #include "Graph.h" #include "Galois/CheckedObject.h" #include <ostream> #include <algorithm> class Point: public Galois::GChecked<void> { Tuple m_t; GNode m_n; long m_id; public: Point(double x, double y, long id): m_t(x,y), m_n(NULL), m_id(id) {} const Tuple& t() const { return m_t; } long id() const { return m_id; } Tuple& t() { return m_t; } long& id() { return m_id; } void addElement(const GNode& n) { m_n = n; } void removeElement(const GNode& n) { if (m_n == n) m_n = NULL; } bool inMesh() const { return m_n != NULL; } GNode someElement() const { return m_n; } void print(std::ostream& os) const { os << "(id: " << m_id << " t: "; m_t.print(os); if (m_n != NULL) os << " SOME)"; else os << " NULL)"; } }; static inline std::ostream& operator<<(std::ostream& os, const Point& rhs) { rhs.print(os); return os; } #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/delaunaytriangulation/Cavity.h
/** A cavity -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2012, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author Xin Sui <[email protected]> * @author Donald Nguyen <[email protected]> */ #ifndef CAVITY_H #define CAVITY_H #include "Graph.h" #include <vector> //! A cavity which will be retrangulated template<typename Alloc=std::allocator<char> > class Cavity: private boost::noncopyable { typedef typename Alloc::template rebind<GNode>::other GNodeVectorAlloc; typedef std::vector<GNode, GNodeVectorAlloc> GNodeVector; typedef typename Alloc::template rebind<std::pair<GNode,int>>::other GNodeIntPairVectorAlloc; typedef std::vector<std::pair<GNode,int>, GNodeIntPairVectorAlloc> GNodeIntPairVector; struct InCircumcenter { const Graph& graph; Tuple tuple; InCircumcenter(const Graph& g, const Tuple& t): graph(g), tuple(t) { } bool operator()(const GNode& n) const { Element& e = graph.getData(n, Galois::MethodFlag::NONE); return e.inCircle(tuple); } }; Searcher<Alloc> searcher; GNodeVector newNodes; GNodeIntPairVector outside; GNode center; Point* point; Graph& graph; const Alloc& alloc; //! Find triangles that border cavity but are not in the cavity void findOutside() { for (typename Searcher<Alloc>::GNodeVector::iterator ii = searcher.inside.begin(), ei = searcher.inside.end(); ii != ei; ++ii) { for (Graph::edge_iterator jj = graph.edge_begin(*ii, Galois::MethodFlag::NONE), ej = graph.edge_end(*ii, Galois::MethodFlag::NONE); jj != ej; ++jj) { GNode n = graph.getEdgeDst(jj); // i.e., if (!e.boundary() && e.inCircle(point->t())) if (std::find(searcher.matches.begin(), searcher.matches.end(), n) != searcher.matches.end()) continue; int index = graph.getEdgeData(graph.findEdge(n, *ii, Galois::MethodFlag::NONE)); outside.push_back(std::make_pair(n, index)); Element& e = graph.getData(n, Galois::MethodFlag::NONE); Point* p2 = e.getPoint(index); Point* p3 = e.getPoint((index + 1) % 3); p2->get(Galois::MethodFlag::CHECK_CONFLICT); p3->get(Galois::MethodFlag::CHECK_CONFLICT); } } } void addElements() { GNodeVector newNodes(alloc); // Create new nodes for (typename GNodeIntPairVector::iterator ii = outside.begin(), ei = outside.end(); ii != ei; ++ii) { const GNode& n = ii->first; int& index = ii->second; Element& e = graph.getData(n, Galois::MethodFlag::NONE); Point* p2 = e.getPoint(index); Point* p3 = e.getPoint((index + 1) % 3); Element newE(point, p2, p3); GNode newNode = graph.createNode(newE); graph.addNode(newNode, Galois::MethodFlag::NONE); point->addElement(newNode); p2->addElement(newNode); p3->addElement(newNode); graph.getEdgeData(graph.addEdge(newNode, n, Galois::MethodFlag::NONE)) = 1; graph.getEdgeData(graph.addEdge(n, newNode, Galois::MethodFlag::NONE)) = index; newNodes.push_back(newNode); } // Update new node connectivity for (unsigned i = 0; i < newNodes.size(); ++i) { const GNode& n1 = newNodes[i]; const Element& e1 = graph.getData(n1, Galois::MethodFlag::NONE); for (unsigned j = i + 1; j < newNodes.size(); ++j) { if (i != j) { const GNode& n2 = newNodes[j]; const Element& e2 = graph.getData(n2, Galois::MethodFlag::NONE); for (int x = 2; x >= 1; --x) { for (int y = 2; y >= 1; --y) { if (e1.getPoint(x) == e2.getPoint(y)) { int indexForNewNode = x & 2; int indexForNode = y & 2; graph.getEdgeData(graph.addEdge(n1, n2, Galois::MethodFlag::NONE)) = indexForNewNode; graph.getEdgeData(graph.addEdge(n2, n1, Galois::MethodFlag::NONE)) = indexForNode; } } } } } } } void removeElements() { for (typename Searcher<Alloc>::GNodeVector::iterator ii = searcher.matches.begin(), ei = searcher.matches.end(); ii != ei; ++ii) { graph.removeNode(*ii, Galois::MethodFlag::NONE); } } public: Cavity(Graph& g, const Alloc& a = Alloc()): searcher(g, a), newNodes(a), outside(a), graph(g), alloc(a) { } void init(const GNode& c, Point* p) { center = c; point = p; } void build() { assert(graph.getData(center).inCircle(point->t())); searcher.findAll(center, InCircumcenter(graph, point->t())); assert(!searcher.inside.empty()); findOutside(); } void update() { removeElements(); addElements(); } }; #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/delaunaytriangulation/Element.cpp
/** An element (i.e., a triangle or a boundary line) -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2012, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author Xin Sui <[email protected]> * @author Donald Nguyen <[email protected]> */ #include "Element.h" #include "Point.h" std::ostream& operator<<(std::ostream& out, const Element& e) { return e.print(out); } bool Element::inTriangle(const Tuple& p) const { if (boundary()) return false; const Tuple& p1 = points[0]->t(); const Tuple& p2 = points[1]->t(); const Tuple& p3 = points[2]->t(); if ((p1 == p) || (p2 == p) || (p3 == p)) { return false; } int count = 0; double px = p.x(); double py = p.y(); double p1x = p1.x(); double p1y = p1.y(); double p2x = p2.x(); double p2y = p2.y(); double p3x = p3.x(); double p3y = p3.y(); if (p2x < p1x) { if ((p2x < px) && (p1x >= px)) { if (((py - p2y) * (p1x - p2x)) < ((px - p2x) * (p1y - p2y))) { count = 1; } } } else { if ((p1x < px) && (p2x >= px)) { if (((py - p1y) * (p2x - p1x)) < ((px - p1x) * (p2y - p1y))) { count = 1; } } } if (p3x < p2x) { if ((p3x < px) && (p2x >= px)) { if (((py - p3y) * (p2x - p3x)) < ((px - p3x) * (p2y - p3y))) { if (count == 1) { return false; } count++; } } } else { if ((p2x < px) && (p3x >= px)) { if (((py - p2y) * (p3x - p2x)) < ((px - p2x) * (p3y - p2y))) { if (count == 1) { return false; } count++; } } } if (p1x < p3x) { if ((p1x < px) && (p3x >= px)) { if (((py - p1y) * (p3x - p1x)) < ((px - p1x) * (p3y - p1y))) { if (count == 1) { return false; } count++; } } } else { if ((p3x < px) && (p1x >= px)) { if (((py - p3y) * (p1x - p3x)) < ((px - p3x) * (p1y - p3y))) { if (count == 1) { return false; } count++; } } } return count == 1; } bool Element::clockwise() const { assert(!boundary()); double t1_x = points[0]->t().x(); double t1_y = points[0]->t().y(); double t2_x = points[1]->t().x(); double t2_y = points[1]->t().y(); double t3_x = points[2]->t().x(); double t3_y = points[2]->t().y(); double counter_clockwise = (t2_x - t1_x) * (t3_y - t1_y) - (t3_x - t1_x) * (t2_y - t1_y); return counter_clockwise < 0; } bool Element::inCircle(const Tuple& p) const { if (boundary()) return false; // This version computes the determinant of a matrix including the // coordinates of each points + distance of these points to the origin // in order to check if a point is inside a triangle or not double t1_x = points[0]->t().x(); double t1_y = points[0]->t().y(); double t2_x = points[1]->t().x(); double t2_y = points[1]->t().y(); double t3_x = points[2]->t().x(); double t3_y = points[2]->t().y(); double p_x = p.x(); double p_y = p.y(); // Check if the points (t1,t2,t3) are sorted clockwise or // counter-clockwise: // -> counter_clockwise > 0 => counter clockwise // -> counter_clockwise = 0 => degenerated triangle // -> counter_clockwise < 0 => clockwise double counter_clockwise = (t2_x - t1_x) * (t3_y - t1_y) - (t3_x - t1_x) * (t2_y - t1_y); // If the triangle is degenerate, then the triangle should be updated if (counter_clockwise == 0.0) { return true; } // Compute the following determinant: // | t1_x-p_x t1_y-p_y (t1_x-p_x)^2+(t1_y-p_y)^2 | // | t2_x-p_x t2_y-p_y (t2_x-p_x)^2+(t2_y-p_y)^2 | // | t3_x-p_x t3_y-p_y (t3_x-p_x)^2+(t3_y-p_y)^2 | // // If the determinant is >0 then the point (p_x,p_y) is inside the // circumcircle of the triangle (t1,t2,t3). // Value of columns 1 and 2 of the matrix double t1_p_x, t1_p_y, t2_p_x, t2_p_y, t3_p_x, t3_p_y; // Determinant of minors extracted from columns 1 and 2 // (det_t3_t1_m corresponds to the opposite) double det_t1_t2, det_t2_t3, det_t3_t1_m; // Values of the column 3 of the matrix double t1_col3, t2_col3, t3_col3; t1_p_x = t1_x - p_x; t1_p_y = t1_y - p_y; t2_p_x = t2_x - p_x; t2_p_y = t2_y - p_y; t3_p_x = t3_x - p_x; t3_p_y = t3_y - p_y; det_t1_t2 = t1_p_x * t2_p_y - t2_p_x * t1_p_y; det_t2_t3 = t2_p_x * t3_p_y - t3_p_x * t2_p_y; det_t3_t1_m = t3_p_x * t1_p_y - t1_p_x * t3_p_y; t1_col3 = t1_p_x * t1_p_x + t1_p_y * t1_p_y; t2_col3 = t2_p_x * t2_p_x + t2_p_y * t2_p_y; t3_col3 = t3_p_x * t3_p_x + t3_p_y * t3_p_y; double det = t1_col3 * det_t2_t3 + t2_col3 * det_t3_t1_m + t3_col3 * det_t1_t2; // If the points are enumerated in clockwise, then negate the result if (counter_clockwise < 0) { return det < 0; } return det > 0; } std::ostream& Element::print(std::ostream& out) const { out << '['; for (int i = 0; i < dim(); ++i) { out << points[i]->id() << " "; points[i]->print(out); out << (i < (dim() - 1) ? ", " : ""); } out << ']'; return out; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/delaunaytriangulation/Graph.h
/** -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2012, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @section Description * * @author Xin Sui <[email protected]> * @author Donald Nguyen <[email protected]> */ #ifndef GRAPH_H #define GRAPH_H #include "Element.h" #include "Galois/optional.h" #include "Galois/Graph/Graph.h" #include <vector> #include <deque> typedef Galois::Graph::FirstGraph<Element,char,true> Graph; typedef Graph::GraphNode GNode; //! Factor out common graph traversals template<typename Alloc=std::allocator<char> > struct Searcher: private boost::noncopyable { typedef Alloc allocator_type; typedef typename Alloc::template rebind<GNode>::other GNodeVectorAlloc; typedef std::vector<GNode, GNodeVectorAlloc> GNodeVector; struct Marker { GNodeVector seen; Marker(Graph&, const Alloc& a): seen(a) { } void mark(GNode n) { seen.push_back(n); } bool hasMark(GNode n) { return std::find(seen.begin(), seen.end(), n) != seen.end(); } }; Graph& graph; GNodeVector matches, inside; const allocator_type& alloc; Searcher(Graph& g, const Alloc& a = allocator_type()): graph(g), matches(a), inside(a), alloc(a) { } struct DetLess: public std::binary_function<GNode,GNode,bool> { Graph& g; DetLess(Graph& x): g(x) { } bool operator()(GNode a, GNode b) const { Element& e1 = g.getData(a, Galois::MethodFlag::NONE); Element& e2 = g.getData(b, Galois::MethodFlag::NONE); for (int i = 0; i < 3; ++i) { uintptr_t v1 = (i < 2 || !e1.boundary()) ? reinterpret_cast<uintptr_t>(e1.getPoint(i)) : 0; uintptr_t v2 = (i < 2 || !e2.boundary()) ? reinterpret_cast<uintptr_t>(e2.getPoint(i)) : 0; if (v1 < v2) return true; else if (v1 > v2) return false; } return false; } }; void removeDupes(GNodeVector& v) { std::sort(v.begin(), v.end(), DetLess(graph)); typename GNodeVector::iterator end = std::unique(v.begin(), v.end()); v.resize(end - v.begin()); } template<typename Pred> void find_(const GNode& start, const Pred& pred, bool all) { typedef Galois::optional<GNode> SomeGNode; typedef typename Alloc::template rebind<std::pair<GNode,SomeGNode>>::other WorklistAlloc; typedef std::deque<std::pair<GNode,SomeGNode>, WorklistAlloc> Worklist; Worklist wl(alloc); wl.push_back(std::make_pair(start, SomeGNode())); Marker marker(graph, alloc); while (!wl.empty()) { GNode cur = wl.front().first; SomeGNode prev = wl.front().second; wl.pop_front(); if (!graph.containsNode(cur, Galois::MethodFlag::CHECK_CONFLICT)) continue; if (marker.hasMark(cur)) continue; // NB(ddn): Technically this makes DelaunayTriangulation.cpp::Process not cautious if (!all) marker.mark(cur); bool matched = false; if (pred(cur)) { matched = true; matches.push_back(cur); if (all) { marker.mark(cur); } else break; // Found it } else { if (all && prev) inside.push_back(*prev); } // Search neighbors (a) when matched and looking for all or (b) when no match and looking // for first if (matched == all) { for (Graph::edge_iterator ii = graph.edge_begin(cur, Galois::MethodFlag::CHECK_CONFLICT), ee = graph.edge_end(cur, Galois::MethodFlag::CHECK_CONFLICT); ii != ee; ++ii) { GNode dst = graph.getEdgeDst(ii); wl.push_back(std::make_pair(dst, SomeGNode(cur))); } } } if (all) { removeDupes(matches); removeDupes(inside); } } //! Find the first occurance of element matching pred template<typename Pred> void findFirst(const GNode& start, const Pred& p) { find_(start, p, false); } //! Find all the elements matching pred (assuming monotonic predicate) template<typename Pred> void findAll(const GNode& start, const Pred& p) { find_(start, p, true); return; } }; #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/delaunaytriangulation/QuadTree.h
/** A quad-tree -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2012, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author Donald Nguyen <[email protected]> */ #ifndef QUADTREE_H #define QUADTREE_H #include "Point.h" #include "Galois/Galois.h" #include "Galois/Accumulator.h" #include <boost/iterator/transform_iterator.hpp> #include <boost/array.hpp> #include <limits> inline int getIndex(const Tuple& a, const Tuple& b) { int index = 0; for (int i = 0; i < 2; ++i) { if (a[i] < b[i]) { index += 1 << i; } } return index; } inline void makeNewCenter(int index, const Tuple& center, double radius, Tuple& newCenter) { newCenter = center; for (int i = 0; i < 2; ++i) { newCenter[i] += (index & (1 << i)) > 0 ? radius : -radius; } } static const int maxLeafSize = 16; /** * Finds points nearby a given point. */ class PQuadTree { struct FindResult { Point* p; double best; }; struct DerefPointer: public std::unary_function<Point*,Point> { Point operator()(Point* p) const { return *p; } }; struct Node { typedef boost::array<Point*,maxLeafSize> PointsTy; Node* child[4]; PointsTy* points; int size; //! Make internal node explicit Node() { memset(child, 0, sizeof(*child) * 4); points = NULL; } //! Make leaf node Node(Point* p, PointsTy* ps) { memset(child, 0, sizeof(*child) * 4); points = ps; points->at(0) = p; size = 1; } bool isLeaf() const { return points != NULL; } }; void deleteNode(Node* root) { if (root->isLeaf()) { pointsAlloc.destroy(root->points); pointsAlloc.deallocate(root->points, 1); } else { for (int i = 0; i < 4; ++i) { if (root->child[i]) deleteNode(root->child[i]); } } nodeAlloc.destroy(root); nodeAlloc.deallocate(root, 1); } Node* newNode() { Node* n = nodeAlloc.allocate(1); nodeAlloc.construct(n, Node()); return n; } Node* newNode(Point *p) { Node* n = nodeAlloc.allocate(1); Node::PointsTy* ps = pointsAlloc.allocate(1); pointsAlloc.construct(ps, Node::PointsTy()); nodeAlloc.construct(n, Node(p, ps)); return n; } //! Provide appropriate initial values for reduction template<bool isMax> struct MTuple: public Tuple { MTuple(): Tuple(isMax ? std::numeric_limits<TupleDataTy>::min() : std::numeric_limits<TupleDataTy>::max()) { } MTuple(const Tuple& t): Tuple(t) { } }; template<bool isMax> struct MTupleReducer { void operator()(MTuple<isMax>& lhs, const MTuple<isMax>& rhs) const { for (int i = 0; i < 2; ++i) lhs[i] = isMax ? std::max(lhs[i], rhs[i]) : std::min(lhs[i], rhs[i]); } }; struct MinBox: public Galois::GReducible<MTuple<false>, MTupleReducer<false> > { MinBox() { } }; struct MaxBox: public Galois::GReducible<MTuple<true>, MTupleReducer<true> > { MaxBox() { } }; struct ComputeBox { MinBox& least; MaxBox& most; ComputeBox(MinBox& l, MaxBox& m): least(l), most(m) { } void operator()(const Point* p) { least.update(p->t()); most.update(p->t()); } }; template<typename IterTy> struct WorkItem { IterTy begin; IterTy end; Tuple center; double radius; Node* root; PQuadTree* self; WorkItem(PQuadTree* s, IterTy b, IterTy e, Node* n, Tuple c, double r): begin(b), end(e), center(c), radius(r), root(n), self(s) { } void operator()() { for (; begin != end; ++begin) { self->add(root, *begin, center, radius); } } }; template<typename IterTy> struct PAdd { void operator()(WorkItem<IterTy>& w) { w(); } void operator()(WorkItem<IterTy>& w, Galois::UserContext<WorkItem<IterTy> >&) { w(); } }; struct Split: public std::unary_function<Point*,bool> { int index; TupleDataTy pivot; Split(int i, TupleDataTy p): index(i), pivot(p) { } bool operator()(Point* p) { return p->t()[index] < pivot; } }; Tuple m_center; double m_radius; Node* m_root; Galois::Runtime::MM::FSBGaloisAllocator<Node> nodeAlloc; Galois::Runtime::MM::FSBGaloisAllocator<Node::PointsTy> pointsAlloc; template<typename IterTy> void init(IterTy begin, IterTy end) { MinBox least; MaxBox most; Galois::do_all(begin, end, ComputeBox(least, most)); //std::for_each(begin, end, ComputeBox(least, most)); MTuple<true> mmost = most.reduce(); MTuple<false> lleast = least.reduce(); m_radius = std::max(mmost.x() - lleast.x(), mmost.y() - lleast.y()) / 2.0; m_center = lleast; m_center.x() += m_radius; m_center.y() += m_radius; } template<typename IterTy,typename OutIterTy> void divideWork(IterTy begin, IterTy end, Node* root, Tuple center, double radius, OutIterTy& out, int depth) { if (depth == 0 || std::distance(begin, end) <= 16) { *out++ = WorkItem<IterTy>(this, begin, end, root, center, radius); return; } IterTy its[5]; its[0] = begin; its[4] = end; its[2] = std::partition(its[0], its[4], Split(1, center[1])); its[1] = std::partition(its[0], its[2], Split(0, center[0])); its[3] = std::partition(its[2], its[4], Split(0, center[0])); radius *= 0.5; --depth; for (int i = 0; i < 4; ++i) { Tuple newC; root->child[i] = newNode(); makeNewCenter(i, center, radius, newC); divideWork(its[i], its[i+1], root->child[i], newC, radius, out, depth); } } bool couldBeCloser(const Point* p, const Tuple& center, double radius, FindResult& result) { if (result.p == NULL) return true; const Tuple& t = p->t(); double d = 0; for (int i = 0; i < t.dim(); ++i) { double min = center[i] - radius - t[i]; double max = center[i] + radius - t[i]; d += std::min(min*min, max*max); } return d < result.best; } bool find(Node* root, const Point* p, const Tuple& center, double radius, FindResult& result) { if (root->isLeaf()) { bool retval = false; const Tuple& t0 = p->t(); for (int i = 0; i < root->size; ++i) { const Point* o = root->points->at(i); if (!o->inMesh()) continue; double d = 0; const Tuple& t1 = o->t(); for (int j = 0; j < t0.dim(); ++j) { double v = t0[j] - t1[j]; d += v * v; } if (result.p == NULL || d < result.best) { result.p = root->points->at(i); result.best = d; retval = true; } } return retval; } // Search, starting at closest quadrant to p radius *= 0.5; int start = getIndex(center, p->t()); for (int i = 0; i < 4; ++i) { int index = (start + i) % 4; Node* kid = root->child[index]; if (kid != NULL) { Tuple newCenter; makeNewCenter(index, center, radius, newCenter); if (couldBeCloser(p, newCenter, radius, result)) { if (false) { // exhaustive find(kid, p, newCenter, radius, result); } else { // return only first if (find(kid, p, newCenter, radius, result)) return true; } } } } return false; } void makeInternal(Node* root, const Tuple& center, double radius) { assert(root->isLeaf()); Node::PointsTy* points = root->points; root->points = NULL; for (Node::PointsTy::iterator ii = points->begin(), ei = points->begin() + root->size; ii != ei; ++ii) { add(root, *ii, center, radius); } pointsAlloc.destroy(points); pointsAlloc.deallocate(points, 1); } void add(Node* root, Point* p, const Tuple& center, double radius) { if (root->isLeaf()) { if (root->size < maxLeafSize) { root->points->at(root->size++) = p; } else { makeInternal(root, center, radius); add(root, p, center, radius); } return; } int index = getIndex(center, p->t()); Node*& kid = root->child[index]; if (kid == NULL) { kid = newNode(p); } else { radius *= 0.5; assert(radius != 0.0); Tuple newCenter; makeNewCenter(index, center, radius, newCenter); add(kid, p, newCenter, radius); } } template<typename OutputTy> void output(Node* root, OutputTy out) { if (root->isLeaf()) { std::copy( boost::make_transform_iterator(root->points->begin(), DerefPointer()), boost::make_transform_iterator(root->points->begin() + root->size, DerefPointer()), out); } else { for (int i = 0; i < 4; ++i) { Node* kid = root->child[i]; if (kid != NULL) output(kid, out); } } } public: template<typename IterTy> PQuadTree(IterTy begin, IterTy end) { m_root = newNode(); init(begin, end); typedef std::vector<Point*> PointsBufTy; typedef WorkItem<PointsBufTy::iterator> WIT; typedef std::vector<WIT> WorkTy; typedef Galois::WorkList::dChunkedLIFO<1> WL; PointsBufTy points; std::copy(begin, end, std::back_inserter(points)); WorkTy work; std::back_insert_iterator<WorkTy> it(work); divideWork(points.begin(), points.end(), m_root, m_center, m_radius, it, 4); Galois::for_each(work.begin(), work.end(), PAdd<PointsBufTy::iterator>(), Galois::wl<WL>()); } ~PQuadTree() { deleteNode(m_root); } template<typename OutputTy> void output(OutputTy out) { if (m_root != NULL) { output(m_root, out); } } //! Find point nearby to p bool find(const Point* p, Point*& result) { FindResult r; r.p = NULL; if (m_root) { find(m_root, p, m_center, m_radius, r); if (r.p != NULL) { result = r.p; return true; } } return false; } }; /** * Finds points nearby a given point. */ class SQuadTree { struct FindResult { Point* p; double best; }; struct DerefPointer: public std::unary_function<Point*,Point> { Point operator()(Point* p) const { return *p; } }; struct Node { Node* child[4]; Point** points; int size; bool isLeaf() const { return points != NULL; } void makeInternal(const Tuple& center, double radius) { memset(child, 0, sizeof(*child) * 4); Point** begin = points; points = NULL; for (Point **p = begin, **end = begin + size; p != end; ++p) { add(*p, center, radius); } delete [] begin; } void add(Point* p, const Tuple& center, double radius) { if (isLeaf()) { if (size < maxLeafSize) { points[size] = p; ++size; } else { makeInternal(center, radius); add(p, center, radius); } return; } int index = getIndex(center, p->t()); Node*& kid = child[index]; if (kid == NULL) { kid = new Node(); kid->points = new Point*[maxLeafSize]; kid->points[0] = p; kid->size = 1; } else { radius *= 0.5; assert(radius != 0.0); Tuple newCenter; makeNewCenter(index, center, radius, newCenter); kid->add(p, newCenter, radius); } } bool couldBeCloser(const Point* p, const Tuple& center, double radius, FindResult& result) { if (result.p == NULL) return true; const Tuple& t = p->t(); double d = 0; for (int i = 0; i < t.dim(); ++i) { double min = center[i] - radius - t[i]; double max = center[i] + radius - t[i]; d += std::min(min*min, max*max); } return d < result.best; } void find(const Point* p, const Tuple& center, double radius, FindResult& result) { if (isLeaf()) { const Tuple& t0 = p->t(); for (int i = 0; i < size; ++i) { double d = 0; const Point* o = points[i]; if (!o->inMesh()) continue; const Tuple& t1 = o->t(); for (int j = 0; j < t0.dim(); ++j) { double v = t0[j] - t1[j]; d += v * v; } if (result.p == NULL || d < result.best) { result.p = points[i]; result.best = d; } } return; } // Search, starting at closest quadrant to p radius *= 0.5; int start = getIndex(center, p->t()); for (int i = 0; i < 4; ++i) { int index = (start + i) % 4; Node* kid = child[index]; if (kid != NULL) { Tuple newCenter; makeNewCenter(index, center, radius, newCenter); if (kid->couldBeCloser(p, newCenter, radius, result)) kid->find(p, newCenter, radius, result); } } } template<typename OutputTy> void output(OutputTy out) { if (isLeaf()) { std::copy( boost::make_transform_iterator(points, DerefPointer()), boost::make_transform_iterator(points + size, DerefPointer()), out); } else { for (int i = 0; i < 4; ++i) { Node* kid = child[i]; if (kid != NULL) kid->output(out); } } } }; void deleteNode(Node*& n) { if (n == NULL) return; if (n->isLeaf()) { delete [] n->points; n->points = NULL; } else { for (int i = 0; i < 4; ++i) { deleteNode(n->child[i]); } } delete n; n = NULL; } template<typename Begin,typename End> void computeBox(Begin begin, End end, Tuple& least, Tuple& most) { least.x() = least.y() = std::numeric_limits<double>::max(); most.x() = most.y() = std::numeric_limits<double>::min(); for (; begin != end; ++begin) { const Tuple& p = (*begin)->t(); for (int i = 0; i < 2; ++i) { if (p[i] < least[i]) least[i] = p[i]; if (p[i] > most[i]) most[i] = p[i]; } } } template<typename Begin,typename End> void init(Begin begin, End end) { Tuple least, most; computeBox(begin, end, least, most); radius = std::max(most.x() - least.x(), most.y() - least.y()) / 2.0; center = least; center.x() += radius; center.y() += radius; } void add(Point* p) { if (root == NULL) { root = new Node(); root->points = NULL; memset(root->child, 0, sizeof(*root->child) * 4); } root->add(p, center, radius); } Tuple center; double radius; Node* root; public: template<typename Begin,typename End> SQuadTree(Begin begin, End end): root(NULL) { init(begin, end); for (; begin != end; ++begin) add(*begin); } ~SQuadTree() { deleteNode(root); } //! Find point nearby to p bool find(const Point* p, Point*& result) { FindResult r; r.p = NULL; if (root) { root->find(p, center, radius, r); if (r.p != NULL) { result = r.p; return true; } } return false; } template<typename OutputTy> void output(OutputTy out) { if (root != NULL) { root->output(out); } } }; typedef PQuadTree QuadTree; #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/delaunaytriangulation/DelaunayTriangulationDet.cpp
/** Delaunay triangulation -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2012, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @section Description * * Delaunay triangulation of points in 2d. * * @author Xin Sui <[email protected]> * @author Donald Nguyen <[email protected]> */ #include "Point.h" #include "Cavity.h" #include "QuadTree.h" #include "Verifier.h" #include "Galois/Galois.h" #include "Galois/Bag.h" #include "Galois/Statistic.h" #include "Lonestar/BoilerPlate.h" #include "llvm/Support/CommandLine.h" #include <boost/iterator/transform_iterator.hpp> #include <boost/iterator/counting_iterator.hpp> #include <algorithm> #include <deque> #include <fstream> #include <iostream> #include <limits> #include <vector> #include <string.h> #include <unistd.h> namespace cll = llvm::cl; static const char* name = "Delaunay Triangulation"; static const char* desc = "Produces a Delaunay triangulation for a set of points"; static const char* url = "delaunay_triangulation"; static cll::opt<std::string> doWriteMesh("writemesh", cll::desc("Write the mesh out to files with basename"), cll::value_desc("basename")); static cll::opt<std::string> doWritePoints("writepoints", cll::desc("Write the (reordered) points to filename"), cll::value_desc("filename")); static cll::opt<bool> noReorderPoints("noreorder", cll::desc("Don't reorder points to improve locality"), cll::init(false)); static cll::opt<std::string> inputname(cll::Positional, cll::desc("<input file>"), cll::Required); enum DetAlgo { nondet, detBase, detPrefix, detDisjoint }; static cll::opt<DetAlgo> detAlgo(cll::desc("Deterministic algorithm:"), cll::values( clEnumVal(nondet, "Non-deterministic"), clEnumVal(detBase, "Base execution"), clEnumVal(detPrefix, "Prefix execution"), clEnumVal(detDisjoint, "Disjoint execution"), clEnumValEnd), cll::init(nondet)); static Graph* graph; struct GetPointer: public std::unary_function<Point&,Point*> { Point* operator()(Point& p) const { return &p; } }; //! Our main functor template<int Version=detBase> struct Process { typedef int tt_needs_per_iter_alloc; typedef int tt_does_not_need_push; typedef Galois::PerIterAllocTy Alloc; QuadTree* tree; struct ContainsTuple { const Graph& graph; Tuple tuple; ContainsTuple(const Graph& g, const Tuple& t): graph(g), tuple(t) { } bool operator()(const GNode& n) const { assert(!graph.getData(n, Galois::MethodFlag::NONE).boundary()); return graph.getData(n, Galois::MethodFlag::NONE).inTriangle(tuple); } }; Process(QuadTree* t): tree(t) { } void computeCenter(const Element& e, Tuple& t) const { for (int i = 0; i < 3; ++i) { const Tuple& o = e.getPoint(i)->t(); for (int j = 0; j < 2; ++j) { t[j] += o[j]; } } for (int j = 0; j < 2; ++j) { t[j] *= 1/3.0; } } void findBestNormal(const Element& element, const Point* p, const Point*& bestP1, const Point*& bestP2) { Tuple center(0); computeCenter(element, center); int scale = element.clockwise() ? 1 : -1; Tuple origin = p->t() - center; // double length2 = origin.x() * origin.x() + origin.y() * origin.y(); bestP1 = bestP2 = NULL; double bestVal = 0.0; for (int i = 0; i < 3; ++i) { int next = i + 1; if (next > 2) next -= 3; const Point* p1 = element.getPoint(i); const Point* p2 = element.getPoint(next); double dx = p2->t().x() - p1->t().x(); double dy = p2->t().y() - p1->t().y(); Tuple normal(scale * -dy, scale * dx); double val = normal.dot(origin); // / length2; if (bestP1 == NULL || val > bestVal) { bestVal = val; bestP1 = p1; bestP2 = p2; } } assert(bestP1 != NULL && bestP2 != NULL && bestVal > 0); } GNode findCorrespondingNode(GNode start, const Point* p1, const Point* p2) { for (Graph::edge_iterator ii = graph->edge_begin(start, Galois::MethodFlag::CHECK_CONFLICT), ei = graph->edge_end(start, Galois::MethodFlag::CHECK_CONFLICT); ii != ei; ++ii) { GNode dst = graph->getEdgeDst(ii); Element& e = graph->getData(dst, Galois::MethodFlag::NONE); int count = 0; for (int i = 0; i < e.dim(); ++i) { if (e.getPoint(i) == p1 || e.getPoint(i) == p2) { if (++count == 2) return dst; } } } GALOIS_DIE("unreachable"); return start; } bool planarSearch(const Point* p, GNode start, GNode& node) { // Try simple hill climbing instead ContainsTuple contains(*graph, p->t()); while (!contains(start)) { Element& element = graph->getData(start, Galois::MethodFlag::CHECK_CONFLICT); if (element.boundary()) { // Should only happen when quad tree returns a boundary point which is rare // There's only one way to go from here assert(std::distance(graph->edge_begin(start), graph->edge_end(start)) == 1); start = graph->getEdgeDst(graph->edge_begin(start, Galois::MethodFlag::CHECK_CONFLICT)); } else { // Find which neighbor will get us to point fastest by computing normal // vectors const Point *p1, *p2; findBestNormal(element, p, p1, p2); start = findCorrespondingNode(start, p1, p2); } } node = start; return true; } bool findContainingElement(const Point* p, GNode& node) { Point* result; if (!tree->find(p, result)) { return false; } result->get(Galois::MethodFlag::CHECK_CONFLICT); GNode someNode = result->someElement(); // Not in mesh yet if (!someNode) { return false; } return planarSearch(p, someNode, node); } struct LocalState { Cavity<Alloc> cav; LocalState(Process<Version>& self, Galois::PerIterAllocTy& alloc): cav(*graph, alloc) { } }; typedef LocalState GaloisDeterministicLocalState; static_assert(Galois::has_deterministic_local_state<Process>::value, "Oops"); //! Parallel operator void operator()(Point* p, Galois::UserContext<Point*>& ctx) { Cavity<Alloc>* cavp = NULL; if (Version == detDisjoint) { bool used; LocalState* localState = (LocalState*) ctx.getLocalState(used); if (used) { localState->cav.update(); return; } else { cavp = &localState->cav; } } p->get(Galois::MethodFlag::CHECK_CONFLICT); assert(!p->inMesh()); GNode node; if (!findContainingElement(p, node)) { // Someone updated an element while we were searching, producing // a semi-consistent state //ctx.push(p); // Current version is safe with locking so this shouldn't happen GALOIS_DIE("unreachable"); return; } assert(graph->getData(node).inTriangle(p->t())); assert(graph->containsNode(node)); if (Version == detDisjoint) { cavp->init(node, p); cavp->build(); } else { Cavity<Alloc> cav(*graph, ctx.getPerIterAlloc()); cav.init(node, p); cav.build(); if (Version == detPrefix) return; cav.update(); } } //! Serial operator void operator()(Point* p) { p->get(Galois::MethodFlag::CHECK_CONFLICT); assert(!p->inMesh()); GNode node; if (!findContainingElement(p, node)) { GALOIS_DIE("Could not find triangle containing point"); return; } assert(graph->getData(node).inTriangle(p->t())); assert(graph->containsNode(node)); Cavity<> cav(*graph); cav.init(node, p); cav.build(); cav.update(); } }; typedef std::deque<Point> PointList; class ReadPoints { void addBoundaryPoints() { double minX, maxX, minY, maxY; minX = minY = std::numeric_limits<double>::max(); maxX = maxY = std::numeric_limits<double>::min(); for (PointList::iterator ii = points.begin(), ei = points.end(); ii != ei; ++ii) { double x = ii->t().x(); double y = ii->t().y(); if (x < minX) minX = x; else if (x > maxX) maxX = x; if (y < minY) minY = y; else if (y > maxY) maxY = y; } size_t size = points.size(); double width = maxX - minX; double height = maxY - minY; double maxLength = std::max(width, height); double centerX = minX + width / 2.0; double centerY = minY + height / 2.0; double radius = maxLength * 3.0; // radius of circle that should cover all points for (int i = 0; i < 3; ++i) { double dX = radius * cos(2*M_PI*(i/3.0)); double dY = radius * sin(2*M_PI*(i/3.0)); points.push_back(Point(centerX + dX, centerY + dY, size + i)); } } void nextLine(std::ifstream& scanner) { scanner.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } void fromTriangle(std::ifstream& scanner) { double x, y; long numPoints; scanner >> numPoints; int dim; scanner >> dim; assert(dim == 2); int k; scanner >> k; // number of attributes assert(k == 0); scanner >> k; // has boundary markers? for (long id = 0; id < numPoints; ++id) { scanner >> k; // point id scanner >> x >> y; nextLine(scanner); points.push_back(Point(x, y, id)); } } void fromPointList(std::ifstream& scanner) { double x, y; // comment line nextLine(scanner); size_t id = 0; while (!scanner.eof()) { scanner >> x >> y; if (x == 0 && y == 0) break; points.push_back(Point(x, y, id++)); x = y = 0; nextLine(scanner); } } PointList& points; public: ReadPoints(PointList& p): points(p) { } void from(const std::string& name) { std::ifstream scanner(name.c_str()); if (!scanner.good()) { GALOIS_DIE("Could not open file: ", name); } if (name.find(".node") == name.size() - 5) { fromTriangle(scanner); } else { fromPointList(scanner); } scanner.close(); if (points.size()) addBoundaryPoints(); else { GALOIS_DIE("No points found in file: ", name); } } }; static void writePoints(const std::string& filename, const PointList& points) { std::ofstream out(filename.c_str()); // <num vertices> <dimension> <num attributes> <has boundary markers> out << points.size() << " 2 0 0\n"; //out.setf(std::ios::fixed, std::ios::floatfield); out.setf(std::ios::scientific, std::ios::floatfield); out.precision(10); long id = 0; for (PointList::const_iterator it = points.begin(), end = points.end(); it != end; ++it) { const Tuple& t = it->t(); out << id++ << " " << t.x() << " " << t.y() << " 0\n"; } out.close(); } //! All Point* refer to elements in this bag Galois::InsertBag<Point> basePoints; size_t maxRounds; Galois::InsertBag<Point*>* rounds; const int roundShift = 4; //! round sizes are portional to (1 << roundsShift) static void copyPointsFromRounds(PointList& points) { for (int i = maxRounds - 1; i >= 0; --i) { Galois::InsertBag<Point*>& pptrs = rounds[i]; for (Galois::InsertBag<Point*>::iterator ii = pptrs.begin(), ei = pptrs.end(); ii != ei; ++ii) { points.push_back(*(*ii)); } } } static void addBoundaryNodes(Point* p1, Point* p2, Point* p3) { Element large_triangle(p1, p2, p3); GNode large_node = graph->createNode(large_triangle); graph->addNode(large_node); p1->addElement(large_node); p2->addElement(large_node); p3->addElement(large_node); Element border_ele1(p1, p2); Element border_ele2(p2, p3); Element border_ele3(p3, p1); GNode border_node1 = graph->createNode(border_ele1); GNode border_node2 = graph->createNode(border_ele2); GNode border_node3 = graph->createNode(border_ele3); graph->addNode(border_node1); graph->addNode(border_node2); graph->addNode(border_node3); graph->getEdgeData(graph->addEdge(large_node, border_node1)) = 0; graph->getEdgeData(graph->addEdge(large_node, border_node2)) = 1; graph->getEdgeData(graph->addEdge(large_node, border_node3)) = 2; graph->getEdgeData(graph->addEdge(border_node1, large_node)) = 0; graph->getEdgeData(graph->addEdge(border_node2, large_node)) = 0; graph->getEdgeData(graph->addEdge(border_node3, large_node)) = 0; } //! Streaming point distribution struct GenerateRounds { typedef Galois::Runtime::PerThreadStorage<unsigned> CounterTy; const PointList& points; size_t log2; GenerateRounds(const PointList& p, size_t l): points(p), log2(l) { } void operator()(size_t index) { const Point& p = points[index]; Point* ptr = &basePoints.push(p); int r = 0; for (size_t i = 0; i < log2; ++i) { size_t mask = (1UL << (i + 1)) - 1; if ((index & mask) == (1UL << i)) { r = i; break; } } rounds[r / roundShift].push(ptr); } }; //! Blocked point distribution (exponentially increasing block size) with points randomized //! within a round static void generateRoundsOld(PointList& points, bool randomize) { size_t counter = 0; size_t round = 0; size_t next = 1 << roundShift; std::vector<Point*> buf; PointList::iterator ii = points.begin(), ei = points.end(); while (ii != ei) { Point* ptr = &basePoints.push(*ii); buf.push_back(ptr); ++ii; if (ii == ei || counter > next) { next *= next; int r = maxRounds - 1 - round; if (randomize) std::random_shuffle(buf.begin(), buf.end()); std::copy(buf.begin(), buf.end(), std::back_inserter(rounds[r])); buf.clear(); ++round; } ++counter; } } static void generateRounds(PointList& points, bool addBoundary) { size_t size = points.size() - 3; size_t log2 = std::max((size_t) floor(log(size) / log(2)), (size_t) 1); maxRounds = log2 / roundShift; rounds = new Galois::InsertBag<Point*>[maxRounds+1]; // +1 for boundary points PointList ordered; //ordered.reserve(size); if (noReorderPoints) { std::copy(points.begin(), points.begin() + size, std::back_inserter(ordered)); generateRoundsOld(ordered, false); } else { // Reorganize spatially QuadTree q( boost::make_transform_iterator(points.begin(), GetPointer()), boost::make_transform_iterator(points.begin() + size, GetPointer())); q.output(std::back_inserter(ordered)); if (true) { if (detAlgo == nondet) { Galois::do_all( boost::counting_iterator<size_t>(0), boost::counting_iterator<size_t>(size), GenerateRounds(ordered, log2)); } else { std::for_each( boost::counting_iterator<size_t>(0), boost::counting_iterator<size_t>(size), GenerateRounds(ordered, log2)); } } else { generateRoundsOld(ordered, true); } } if (!addBoundary) return; // Now, handle boundary points size_t last = points.size(); Point* p1 = &basePoints.push(points[last-1]); Point* p2 = &basePoints.push(points[last-2]); Point* p3 = &basePoints.push(points[last-3]); rounds[maxRounds].push(p1); rounds[maxRounds].push(p2); rounds[maxRounds].push(p3); addBoundaryNodes(p1, p2, p3); } static void readInput(const std::string& filename, bool addBoundary) { PointList points; ReadPoints(points).from(filename); std::cout << "configuration: " << points.size() << " points\n"; graph = new Graph(); #if 1 Galois::preAlloc( 32 * points.size() * sizeof(Element) * 1.5 // mesh is about 2x number of points (for random points) / (Galois::Runtime::MM::pageSize) // in pages ); #else Galois::preAlloc(1 * numThreads // some per-thread state + 2 * points.size() * sizeof(Element) // mesh is about 2x number of points (for random points) * 32 // include graph node size / (Galois::Runtime::MM::pageSize) // in pages ); #endif Galois::reportPageAlloc("MeminfoPre"); Galois::StatTimer T("generateRounds"); T.start(); generateRounds(points, addBoundary); T.stop(); } static void writeMesh(const std::string& filename) { long numTriangles = 0; long numSegments = 0; for (Graph::iterator ii = graph->begin(), ei = graph->end(); ii != ei; ++ii) { Element& e = graph->getData(*ii); if (e.boundary()) { numSegments++; } else { numTriangles++; } } long tid = 0; long sid = 0; std::string elementName(filename); std::string polyName(filename); elementName.append(".ele"); polyName.append(".poly"); std::ofstream eout(elementName.c_str()); std::ofstream pout(polyName.c_str()); // <num triangles> <nodes per triangle> <num attributes> eout << numTriangles << " 3 0\n"; // <num vertices> <dimension> <num attributes> <has boundary markers> // ... // <num segments> <has boundary markers> pout << "0 2 0 0\n"; pout << numSegments << " 1\n"; for (Graph::iterator ii = graph->begin(), ee = graph->end(); ii != ee; ++ii) { const Element& e = graph->getData(*ii); if (e.boundary()) { // <segment id> <vertex> <vertex> <is boundary> pout << sid++ << " " << e.getPoint(0)->id() << " " << e.getPoint(1)->id() << " 1\n"; } else { // <triangle id> <vertex> <vertex> <vertex> [in ccw order] eout << tid++ << " " << e.getPoint(0)->id() << " "; if (e.clockwise()) { eout << e.getPoint(2)->id() << " " << e.getPoint(1)->id() << "\n"; } else { eout << e.getPoint(1)->id() << " " << e.getPoint(2)->id() << "\n"; } } } eout.close(); // <num holes> pout << "0\n"; pout.close(); } static void generateMesh() { typedef Galois::WorkList::AltChunkedLIFO<32> Chunked; for (int i = maxRounds - 1; i >= 0; --i) { Galois::StatTimer BT("buildtree"); BT.start(); Galois::InsertBag<Point*>& tptrs = rounds[i+1]; QuadTree tree(tptrs.begin(), tptrs.end()); BT.stop(); Galois::StatTimer PT("ParallelTime"); PT.start(); Galois::InsertBag<Point*>& pptrs = rounds[i]; switch (detAlgo) { case nondet: Galois::for_each_local(pptrs, Process<>(&tree), Galois::wl<Chunked>()); break; case detBase: Galois::for_each_det(pptrs.begin(), pptrs.end(), Process<>(&tree)); break; case detPrefix: Galois::for_each_det(pptrs.begin(), pptrs.end(), Process<detPrefix>(&tree), Process<>(&tree)); break; case detDisjoint: Galois::for_each_det(pptrs.begin(), pptrs.end(), Process<detDisjoint>(&tree)); break; default: GALOIS_DIE("Unknown algorithm: ", detAlgo); } PT.stop(); } } int main(int argc, char** argv) { Galois::StatManager statManager; LonestarStart(argc, argv, name, desc, url); bool writepoints = doWritePoints.size() > 0; readInput(inputname, !writepoints); if (writepoints) { std::cout << "Writing " << doWritePoints << "\n"; PointList points; copyPointsFromRounds(points); writePoints(doWritePoints, points); delete graph; delete [] rounds; return 0; } const char* name = 0; switch (detAlgo) { case nondet: name = "nondet"; break; case detBase: name = "detBase"; break; case detPrefix: name = "detPrefix"; break; case detDisjoint: name = "detDisjoint"; break; default: name = "unknown"; break; } Galois::Runtime::LL::gInfo("Algorithm ", name); Galois::StatTimer T; T.start(); generateMesh(); T.stop(); std::cout << "mesh size: " << graph->size() << "\n"; Galois::reportPageAlloc("MeminfoPost"); if (!skipVerify) { Verifier verifier; if (!verifier.verify(graph)) { GALOIS_DIE("Triangulation failed"); } std::cout << "Triangulation OK\n"; } if (doWriteMesh.size()) { std::string base = doWriteMesh; std::cout << "Writing " << base << "\n"; writeMesh(base.c_str()); PointList points; // Reordering messes up connection between id and place in pointlist ReadPoints(points).from(inputname); writePoints(base.append(".node"), points); } delete graph; delete [] rounds; return 0; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/delaunaytriangulation/DelaunayTriangulation.cpp
/** Delaunay triangulation -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2012, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @section Description * * Delaunay triangulation of points in 2d. * * @author Xin Sui <[email protected]> * @author Donald Nguyen <[email protected]> */ #include "Point.h" #include "Cavity.h" #include "Verifier.h" #include "Galois/Galois.h" #include "Galois/Bag.h" #include "Galois/Statistic.h" #include "Galois/Graph/SpatialTree.h" #include "Lonestar/BoilerPlate.h" #include "llvm/Support/CommandLine.h" #include <boost/iterator/transform_iterator.hpp> #include <boost/iterator/counting_iterator.hpp> #include <algorithm> #include <deque> #include <fstream> #include <iostream> #include <limits> #include <vector> #include <string.h> #include <unistd.h> namespace cll = llvm::cl; static const char* name = "Delaunay Triangulation"; static const char* desc = "Produces a Delaunay triangulation for a set of points"; static const char* url = "delaunay_triangulation"; static cll::opt<std::string> inputname(cll::Positional, cll::desc("<input file>"), cll::Required); static cll::opt<std::string> doWriteMesh("writemesh", cll::desc("Write the mesh out to files with basename"), cll::value_desc("basename")); static Graph graph; static Galois::Graph::SpatialTree2d<Point*> tree; //! Our main functor struct Process { typedef int tt_needs_per_iter_alloc; typedef int tt_does_not_need_push; typedef Galois::PerIterAllocTy Alloc; struct ContainsTuple { const Graph& graph; Tuple tuple; ContainsTuple(const Graph& g, const Tuple& t): graph(g), tuple(t) { } bool operator()(const GNode& n) const { assert(!graph.getData(n, Galois::MethodFlag::NONE).boundary()); return graph.getData(n, Galois::MethodFlag::NONE).inTriangle(tuple); } }; void computeCenter(const Element& e, Tuple& t) const { for (int i = 0; i < 3; ++i) { const Tuple& o = e.getPoint(i)->t(); for (int j = 0; j < 2; ++j) { t[j] += o[j]; } } for (int j = 0; j < 2; ++j) { t[j] *= 1/3.0; } } void findBestNormal(const Element& element, const Point* p, const Point*& bestP1, const Point*& bestP2) { Tuple center(0); computeCenter(element, center); int scale = element.clockwise() ? 1 : -1; Tuple origin = p->t() - center; // double length2 = origin.x() * origin.x() + origin.y() * origin.y(); bestP1 = bestP2 = NULL; double bestVal = 0.0; for (int i = 0; i < 3; ++i) { int next = i + 1; if (next > 2) next -= 3; const Point* p1 = element.getPoint(i); const Point* p2 = element.getPoint(next); double dx = p2->t().x() - p1->t().x(); double dy = p2->t().y() - p1->t().y(); Tuple normal(scale * -dy, scale * dx); double val = normal.dot(origin); // / length2; if (bestP1 == NULL || val > bestVal) { bestVal = val; bestP1 = p1; bestP2 = p2; } } assert(bestP1 != NULL && bestP2 != NULL && bestVal > 0); } GNode findCorrespondingNode(GNode start, const Point* p1, const Point* p2) { for (Graph::edge_iterator ii = graph.edge_begin(start, Galois::MethodFlag::CHECK_CONFLICT), ei = graph.edge_end(start, Galois::MethodFlag::CHECK_CONFLICT); ii != ei; ++ii) { GNode dst = graph.getEdgeDst(ii); Element& e = graph.getData(dst, Galois::MethodFlag::NONE); int count = 0; for (int i = 0; i < e.dim(); ++i) { if (e.getPoint(i) == p1 || e.getPoint(i) == p2) { if (++count == 2) return dst; } } } GALOIS_DIE("unreachable"); return start; } bool planarSearch(const Point* p, GNode start, GNode& node) { // Try simple hill climbing instead ContainsTuple contains(graph, p->t()); while (!contains(start)) { Element& element = graph.getData(start, Galois::MethodFlag::CHECK_CONFLICT); if (element.boundary()) { // Should only happen when quad tree returns a boundary point which is rare // There's only one way to go from here assert(std::distance(graph.edge_begin(start), graph.edge_end(start)) == 1); start = graph.getEdgeDst(graph.edge_begin(start, Galois::MethodFlag::CHECK_CONFLICT)); } else { // Find which neighbor will get us to point fastest by computing normal // vectors const Point *p1, *p2; findBestNormal(element, p, p1, p2); start = findCorrespondingNode(start, p1, p2); } } node = start; return true; } bool findContainingElement(const Point* p, GNode& node) { Point** rp = tree.find(p->t().x(), p->t().y()); if (!rp) return false; (*rp)->get(Galois::MethodFlag::CHECK_CONFLICT); GNode someNode = (*rp)->someElement(); // Not in mesh yet if (!someNode) { GALOIS_DIE("unreachable"); return false; } return planarSearch(p, someNode, node); } //! Parallel operator GALOIS_ATTRIBUTE_NOINLINE void operator()(Point* p, Galois::UserContext<Point*>& ctx) { p->get(Galois::MethodFlag::CHECK_CONFLICT); assert(!p->inMesh()); GNode node; if (!findContainingElement(p, node)) { // Someone updated an element while we were searching, producing // a semi-consistent state // ctx.push(p); // Current version is safe with locking so this shouldn't happen GALOIS_DIE("unreachable"); return; } assert(graph.getData(node).inTriangle(p->t())); assert(graph.containsNode(node)); Cavity<Alloc> cav(graph, ctx.getPerIterAlloc()); cav.init(node, p); cav.build(); cav.update(); tree.insert(p->t().x(), p->t().y(), p); } }; typedef std::vector<Point> PointList; class ReadPoints { void addBoundaryPoints() { double minX, maxX, minY, maxY; minX = minY = std::numeric_limits<double>::max(); maxX = maxY = std::numeric_limits<double>::min(); for (PointList::iterator ii = points.begin(), ei = points.end(); ii != ei; ++ii) { double x = ii->t().x(); double y = ii->t().y(); if (x < minX) minX = x; else if (x > maxX) maxX = x; if (y < minY) minY = y; else if (y > maxY) maxY = y; } tree.init(minX, minY, maxX, maxY); size_t size = points.size(); double width = maxX - minX; double height = maxY - minY; double maxLength = std::max(width, height); double centerX = minX + width / 2.0; double centerY = minY + height / 2.0; double radius = maxLength * 3.0; // radius of circle that should cover all points for (int i = 0; i < 3; ++i) { double dX = radius * cos(2*M_PI*(i/3.0)); double dY = radius * sin(2*M_PI*(i/3.0)); points.push_back(Point(centerX + dX, centerY + dY, size + i)); } } void nextLine(std::ifstream& scanner) { scanner.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } void fromTriangle(std::ifstream& scanner) { double x, y; long numPoints; scanner >> numPoints; int dim; scanner >> dim; assert(dim == 2); int k; scanner >> k; // number of attributes assert(k == 0); scanner >> k; // has boundary markers? for (long id = 0; id < numPoints; ++id) { scanner >> k; // point id scanner >> x >> y; nextLine(scanner); points.push_back(Point(x, y, id)); } } void fromPointList(std::ifstream& scanner) { double x, y; // comment line nextLine(scanner); size_t id = 0; while (!scanner.eof()) { scanner >> x >> y; if (x == 0 && y == 0) break; points.push_back(Point(x, y, id++)); x = y = 0; nextLine(scanner); } } PointList& points; public: ReadPoints(PointList& p): points(p) { } void from(const std::string& name) { std::ifstream scanner(name.c_str()); if (!scanner.good()) { GALOIS_DIE("Could not open file: ", name); } if (name.find(".node") == name.size() - 5) { fromTriangle(scanner); } else { fromPointList(scanner); } scanner.close(); if (points.size()) addBoundaryPoints(); else { GALOIS_DIE("No points found in file: ", name); } } }; //! All Point* refer to elements in this bag Galois::InsertBag<Point> basePoints; Galois::InsertBag<Point*> ptrPoints; static void addBoundaryNodes(Point* p1, Point* p2, Point* p3) { Element large_triangle(p1, p2, p3); GNode large_node = graph.createNode(large_triangle); graph.addNode(large_node); p1->addElement(large_node); p2->addElement(large_node); p3->addElement(large_node); tree.insert(p1->t().x(), p1->t().y(), p1); Element border_ele1(p1, p2); Element border_ele2(p2, p3); Element border_ele3(p3, p1); GNode border_node1 = graph.createNode(border_ele1); GNode border_node2 = graph.createNode(border_ele2); GNode border_node3 = graph.createNode(border_ele3); graph.addNode(border_node1); graph.addNode(border_node2); graph.addNode(border_node3); graph.getEdgeData(graph.addEdge(large_node, border_node1)) = 0; graph.getEdgeData(graph.addEdge(large_node, border_node2)) = 1; graph.getEdgeData(graph.addEdge(large_node, border_node3)) = 2; graph.getEdgeData(graph.addEdge(border_node1, large_node)) = 0; graph.getEdgeData(graph.addEdge(border_node2, large_node)) = 0; graph.getEdgeData(graph.addEdge(border_node3, large_node)) = 0; } struct insPt { void operator()(Point& p) { Point* pr = &basePoints.push(p); ptrPoints.push(pr); } }; struct centerXCmp { template<typename T> bool operator()(const T& lhs, const T& rhs) const { return lhs.t().x() < rhs.t().x(); } }; struct centerYCmp { template<typename T> bool operator()(const T& lhs, const T& rhs) const { return lhs.t().y() < rhs.t().y(); } }; struct centerYCmpInv { template<typename T> bool operator()(const T& lhs, const T& rhs) const { return rhs.t().y() < lhs.t().y(); } }; template<typename Iter> void divide(const Iter& b, const Iter& e) { if (std::distance(b,e) > 64) { std::sort(b, e, centerXCmp()); Iter m = Galois::split_range(b, e); std::sort(b, m, centerYCmpInv()); std::sort(m, e, centerYCmp()); divide(b, Galois::split_range(b, m)); divide(Galois::split_range(b, m), m); divide(m,Galois::split_range(m, e)); divide(Galois::split_range(m, e), e); } else { std::random_shuffle(b, e); } } void layoutPoints(PointList& points) { divide(points.begin(), points.end() - 3); Galois::do_all(points.begin(), points.end() - 3, insPt()); Point* p1 = &basePoints.push(*(points.end() - 1)); Point* p2 = &basePoints.push(*(points.end() - 2)); Point* p3 = &basePoints.push(*(points.end() - 3)); addBoundaryNodes(p1,p2,p3); } static void readInput(const std::string& filename) { PointList points; ReadPoints(points).from(filename); std::cout << "configuration: " << points.size() << " points\n"; Galois::preAlloc(2 * numThreads // some per-thread state + 2 * points.size() * sizeof(Element) // mesh is about 2x number of points (for random points) * 32 // include graph node size / (Galois::Runtime::MM::pageSize) // in pages ); Galois::reportPageAlloc("MeminfoPre"); layoutPoints(points); } static void writePoints(const std::string& filename, const PointList& points) { std::ofstream out(filename.c_str()); // <num vertices> <dimension> <num attributes> <has boundary markers> out << points.size() << " 2 0 0\n"; //out.setf(std::ios::fixed, std::ios::floatfield); out.setf(std::ios::scientific, std::ios::floatfield); out.precision(10); long id = 0; for (PointList::const_iterator it = points.begin(), end = points.end(); it != end; ++it) { const Tuple& t = it->t(); out << id++ << " " << t.x() << " " << t.y() << " 0\n"; } out.close(); } static void writeMesh(const std::string& filename) { long numTriangles = 0; long numSegments = 0; for (Graph::iterator ii = graph.begin(), ei = graph.end(); ii != ei; ++ii) { Element& e = graph.getData(*ii); if (e.boundary()) { numSegments++; } else { numTriangles++; } } long tid = 0; long sid = 0; std::string elementName(filename); std::string polyName(filename); elementName.append(".ele"); polyName.append(".poly"); std::ofstream eout(elementName.c_str()); std::ofstream pout(polyName.c_str()); // <num triangles> <nodes per triangle> <num attributes> eout << numTriangles << " 3 0\n"; // <num vertices> <dimension> <num attributes> <has boundary markers> // ... // <num segments> <has boundary markers> pout << "0 2 0 0\n"; pout << numSegments << " 1\n"; for (Graph::iterator ii = graph.begin(), ee = graph.end(); ii != ee; ++ii) { const Element& e = graph.getData(*ii); if (e.boundary()) { // <segment id> <vertex> <vertex> <is boundary> pout << sid++ << " " << e.getPoint(0)->id() << " " << e.getPoint(1)->id() << " 1\n"; } else { // <triangle id> <vertex> <vertex> <vertex> [in ccw order] eout << tid++ << " " << e.getPoint(0)->id() << " "; if (e.clockwise()) { eout << e.getPoint(2)->id() << " " << e.getPoint(1)->id() << "\n"; } else { eout << e.getPoint(1)->id() << " " << e.getPoint(2)->id() << "\n"; } } } eout.close(); // <num holes> pout << "0\n"; pout.close(); } static void generateMesh() { typedef Galois::WorkList::AltChunkedLIFO<32> CA; Galois::for_each_local(ptrPoints, Process(), Galois::wl<CA>()); } int main(int argc, char** argv) { Galois::StatManager statManager; LonestarStart(argc, argv, name, desc, url); readInput(inputname); Galois::StatTimer T; T.start(); generateMesh(); T.stop(); std::cout << "mesh size: " << graph.size() << "\n"; Galois::reportPageAlloc("MeminfoPost"); if (!skipVerify) { Verifier verifier; if (!verifier.verify(&graph)) { GALOIS_DIE("Triangulation failed"); } std::cout << "Triangulation OK\n"; } if (doWriteMesh.size()) { std::string base = doWriteMesh; std::cout << "Writing " << base << "\n"; writeMesh(base.c_str()); PointList points; // Reordering messes up connection between id and place in pointlist ReadPoints(points).from(inputname); writePoints(base.append(".node"), points); } return 0; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/spanningtree/SpanningTree.cpp
/** Spanning-tree application -*- C++ -*- * @file * * A simple spanning tree algorithm to demonstrate the Galois system. * * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2012, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author Donald Nguyen <[email protected]> */ #include "Galois/Galois.h" #include "Galois/Accumulator.h" #include "Galois/Bag.h" #include "Galois/Statistic.h" #include "Galois/UnionFind.h" #include "Galois/Graph/LCGraph.h" #include "Galois/ParallelSTL/ParallelSTL.h" #include "llvm/Support/CommandLine.h" #include "Lonestar/BoilerPlate.h" #include <utility> #include <algorithm> #include <iostream> namespace cll = llvm::cl; const char* name = "Spanning Tree Algorithm"; const char* desc = "Computes the spanning forest of a graph"; const char* url = NULL; enum Algo { demo, asynchronous, blockedasync }; static cll::opt<std::string> inputFilename(cll::Positional, cll::desc("<input file>"), cll::Required); static cll::opt<Algo> algo("algo", cll::desc("Choose an algorithm:"), cll::values( clEnumVal(demo, "Demonstration algorithm"), clEnumVal(asynchronous, "Asynchronous"), clEnumVal(blockedasync, "Blocked Asynchronous"), clEnumValEnd), cll::init(blockedasync)); struct Node: public Galois::UnionFindNode<Node> { Node*& component() { return m_component; } }; typedef Galois::Graph::LC_Linear_Graph<Node,void> ::with_numa_alloc<true>::type Graph; typedef Graph::GraphNode GNode; Graph graph; std::ostream& operator<<(std::ostream& os, const Node& n) { os << "[id: " << &n << "]"; return os; } typedef std::pair<GNode,GNode> Edge; Galois::InsertBag<Edge> mst; /** * Construct a spanning forest via a modified BFS algorithm. Intended as a * simple introduction to the Galois system and not intended to particularly * fast. Restrictions: graph must be strongly connected. In this case, the * spanning tree is over the undirected graph created by making the directed * graph symmetric. */ struct DemoAlgo { Node* root; void operator()(GNode src, Galois::UserContext<GNode>& ctx) { for (Graph::edge_iterator ii = graph.edge_begin(src, Galois::MethodFlag::ALL), ei = graph.edge_end(src, Galois::MethodFlag::ALL); ii != ei; ++ii) { GNode dst = graph.getEdgeDst(ii); Node& ddata = graph.getData(dst, Galois::MethodFlag::NONE); if (ddata.component() == root) continue; ddata.component() = root; mst.push(std::make_pair(src, dst)); ctx.push(dst); } } void operator()() { Graph::iterator ii = graph.begin(), ei = graph.end(); if (ii != ei) { root = &graph.getData(*ii); Galois::for_each(*ii, *this); } } }; /** * Like asynchronous connected components algorithm. */ struct AsyncAlgo { struct Merge { Galois::Statistic& emptyMerges; Merge(Galois::Statistic& e): emptyMerges(e) { } void operator()(const GNode& src) const { Node& sdata = graph.getData(src, Galois::MethodFlag::NONE); for (Graph::edge_iterator ii = graph.edge_begin(src, Galois::MethodFlag::NONE), ei = graph.edge_end(src, Galois::MethodFlag::NONE); ii != ei; ++ii) { GNode dst = graph.getEdgeDst(ii); Node& ddata = graph.getData(dst, Galois::MethodFlag::NONE); if (sdata.merge(&ddata)) { mst.push(std::make_pair(src, dst)); } else { emptyMerges += 1; } } } }; //! Normalize component by doing find with path compression struct Normalize { void operator()(const GNode& src) const { Node& sdata = graph.getData(src, Galois::MethodFlag::NONE); sdata.component() = sdata.findAndCompress(); } }; void operator()() { Galois::Statistic emptyMerges("EmptyMerges"); Galois::do_all_local(graph, Merge(emptyMerges), Galois::loopname("Merge"), Galois::do_all_steal(true)); Galois::do_all_local(graph, Normalize(), Galois::loopname("Normalize")); } }; /** * Improve performance of async algorithm by following machine topology. */ struct BlockedAsyncAlgo { struct WorkItem { GNode src; Graph::edge_iterator start; }; struct Merge { typedef int tt_does_not_need_aborts; Galois::InsertBag<WorkItem>& items; //! Add the next edge between components to the worklist template<bool MakeContinuation, int Limit, typename Pusher> void process(const GNode& src, const Graph::edge_iterator& start, Pusher& pusher) { Node& sdata = graph.getData(src, Galois::MethodFlag::NONE); int count = 1; for (Graph::edge_iterator ii = start, ei = graph.edge_end(src, Galois::MethodFlag::NONE); ii != ei; ++ii, ++count) { GNode dst = graph.getEdgeDst(ii); Node& ddata = graph.getData(dst, Galois::MethodFlag::NONE); if (sdata.merge(&ddata)) { mst.push(std::make_pair(src, dst)); if (Limit == 0 || count != Limit) continue; } if (MakeContinuation || (Limit != 0 && count == Limit)) { WorkItem item = { src, ii + 1 }; pusher.push(item); break; } } } void operator()(const GNode& src) { Graph::edge_iterator start = graph.edge_begin(src, Galois::MethodFlag::NONE); if (Galois::Runtime::LL::getPackageForSelf(Galois::Runtime::LL::getTID()) == 0) { process<true, 0>(src, start, items); } else { process<true, 1>(src, start, items); } } void operator()(const WorkItem& item, Galois::UserContext<WorkItem>& ctx) { process<true, 0>(item.src, item.start, ctx); } }; //! Normalize component by doing find with path compression struct Normalize { void operator()(const GNode& src) const { Node& sdata = graph.getData(src, Galois::MethodFlag::NONE); sdata.component() = sdata.findAndCompress(); } }; void operator()() { Galois::InsertBag<WorkItem> items; Merge merge = { items }; Galois::do_all_local(graph, merge, Galois::loopname("Initialize"), Galois::do_all_steal(false)); Galois::for_each_local(items, merge, Galois::loopname("Merge"), Galois::wl<Galois::WorkList::dChunkedFIFO<128> >()); Galois::do_all_local(graph, Normalize(), Galois::loopname("Normalize")); } }; struct is_bad_graph { bool operator()(const GNode& n) const { Node& me = graph.getData(n); for (Graph::edge_iterator ii = graph.edge_begin(n), ei = graph.edge_end(n); ii != ei; ++ii) { GNode dst = graph.getEdgeDst(ii); Node& data = graph.getData(dst); if (me.component() != data.component()) { std::cerr << "not in same component: " << me << " and " << data << "\n"; return true; } } return false; } }; struct is_bad_mst { bool operator()(const Edge& e) const { return graph.getData(e.first).component() != graph.getData(e.second).component(); } }; struct CheckAcyclic { struct Accum { Galois::GAccumulator<unsigned> roots; }; Accum* accum; void operator()(const GNode& n) { Node& data = graph.getData(n); if (data.component() == &data) accum->roots += 1; } bool operator()() { Accum a; accum = &a; Galois::do_all_local(graph, *this); unsigned numRoots = a.roots.reduce(); unsigned numEdges = std::distance(mst.begin(), mst.end()); if (graph.size() - numRoots != numEdges) { std::cerr << "Generated graph is not a forest. " << "Expected " << graph.size() - numRoots << " edges but " << "found " << numEdges << "\n"; return false; } std::cout << "Num trees: " << numRoots << "\n"; std::cout << "Tree edges: " << numEdges << "\n"; return true; } }; bool verify() { if (Galois::ParallelSTL::find_if(graph.begin(), graph.end(), is_bad_graph()) == graph.end()) { if (Galois::ParallelSTL::find_if(mst.begin(), mst.end(), is_bad_mst()) == mst.end()) { CheckAcyclic c; return c(); } } return false; } template<typename Algo> void run() { Algo algo; Galois::StatTimer T; T.start(); algo(); T.stop(); } int main(int argc, char** argv) { Galois::StatManager statManager; LonestarStart(argc, argv, name, desc, url); Galois::StatTimer Tinitial("InitializeTime"); Tinitial.start(); Galois::Graph::readGraph(graph, inputFilename); std::cout << "Num nodes: " << graph.size() << "\n"; Tinitial.stop(); //Galois::preAlloc(numThreads + graph.size() / Galois::Runtime::MM::pageSize * 60); Galois::reportPageAlloc("MeminfoPre"); switch (algo) { case demo: run<DemoAlgo>(); break; case asynchronous: run<AsyncAlgo>(); break; case blockedasync: run<BlockedAsyncAlgo>(); break; default: std::cerr << "Unknown algo: " << algo << "\n"; } Galois::reportPageAlloc("MeminfoPost"); if (!skipVerify && !verify()) { std::cerr << "verification failed\n"; assert(0 && "verification failed"); abort(); } return 0; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/spanningtree/CMakeLists.txt
app(spanningtree)
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/independentset/CMakeLists.txt
app(independentset)
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/independentset/IndependentSet.cpp
/** Maximal independent set application -*- C++ -*- * @file * * A simple spanning tree algorithm to demostrate the Galois system. * * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2012, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author Donald Nguyen <[email protected]> */ #include "Galois/Galois.h" #include "Galois/Bag.h" #include "Galois/Statistic.h" #include "Galois/Graph/LCGraph.h" #include "Galois/ParallelSTL/ParallelSTL.h" #ifdef GALOIS_USE_EXP #include "Galois/Runtime/ParallelWorkInline.h" #endif #include "llvm/Support/CommandLine.h" #include "Lonestar/BoilerPlate.h" #include <utility> #include <vector> #include <algorithm> #include <iostream> const char* name = "Maximal Independent Set"; const char* desc = "Computes a maximal independent set (not maximum) of nodes in a graph"; const char* url = "independent_set"; enum Algo { serial, pull, nondet, detBase, detPrefix, detDisjoint, orderedBase, }; namespace cll = llvm::cl; static cll::opt<std::string> filename(cll::Positional, cll::desc("<input file>"), cll::Required); static cll::opt<Algo> algo(cll::desc("Choose an algorithm:"), cll::values( clEnumVal(serial, "Serial"), clEnumVal(pull, "Pull-based (deterministic)"), clEnumVal(nondet, "Non-deterministic"), clEnumVal(detBase, "Base deterministic execution"), clEnumVal(detPrefix, "Prefix deterministic execution"), clEnumVal(detDisjoint, "Disjoint deterministic execution"), clEnumVal(orderedBase, "Base ordered execution"), clEnumValEnd), cll::init(nondet)); enum MatchFlag { UNMATCHED, OTHER_MATCHED, MATCHED }; struct Node { MatchFlag flag; MatchFlag pendingFlag; Node() : flag(UNMATCHED), pendingFlag(UNMATCHED) { } }; struct SerialAlgo { typedef Galois::Graph::LC_InlineEdge_Graph<Node,void> ::with_numa_alloc<true>::type ::with_no_lockable<true>::type ::with_compressed_node_ptr<true>::type Graph; typedef Graph::GraphNode GNode; void operator()(Graph& graph) { for (Graph::iterator ii = graph.begin(), ei = graph.end(); ii != ei; ++ii) { if (findUnmatched(graph, *ii)) match(graph, *ii); } } bool findUnmatched(Graph& graph, GNode src) { Node& me = graph.getData(src); if (me.flag != UNMATCHED) return false; for (Graph::edge_iterator ii = graph.edge_begin(src), ei = graph.edge_end(src); ii != ei; ++ii) { GNode dst = graph.getEdgeDst(ii); Node& data = graph.getData(dst); if (data.flag == MATCHED) return false; } return true; } void match(Graph& graph, GNode src) { Node& me = graph.getData(src); for (Graph::edge_iterator ii = graph.edge_begin(src), ei = graph.edge_end(src); ii != ei; ++ii) { GNode dst = graph.getEdgeDst(ii); Node& data = graph.getData(dst); data.flag = OTHER_MATCHED; } me.flag = MATCHED; } }; //! Basic operator for default and deterministic scheduling template<int Version=detBase> struct Process { typedef int tt_does_not_need_push; typedef int tt_needs_per_iter_alloc; // For LocalState typedef Galois::Graph::LC_InlineEdge_Graph<Node,void> ::with_numa_alloc<true>::type ::with_compressed_node_ptr<true>::type Graph; typedef Graph::GraphNode GNode; struct LocalState { bool mod; LocalState(Process<Version>& self, Galois::PerIterAllocTy& alloc): mod(false) { } }; typedef LocalState GaloisDeterministicLocalState; static_assert(Galois::has_deterministic_local_state<Process>::value, "Oops"); Graph& graph; Process(Graph& g): graph(g) { } template<Galois::MethodFlag Flag> bool build(GNode src) { Node& me = graph.getData(src, Flag); if (me.flag != UNMATCHED) return false; for (Graph::edge_iterator ii = graph.edge_begin(src, Galois::MethodFlag::NONE), ei = graph.edge_end(src, Galois::MethodFlag::NONE); ii != ei; ++ii) { GNode dst = graph.getEdgeDst(ii); Node& data = graph.getData(dst, Flag); if (data.flag == MATCHED) return false; } return true; } void modify(GNode src) { Node& me = graph.getData(src, Galois::MethodFlag::NONE); for (Graph::edge_iterator ii = graph.edge_begin(src, Galois::MethodFlag::NONE), ei = graph.edge_end(src, Galois::MethodFlag::NONE); ii != ei; ++ii) { GNode dst = graph.getEdgeDst(ii); Node& data = graph.getData(dst, Galois::MethodFlag::NONE); data.flag = OTHER_MATCHED; } me.flag = MATCHED; } void operator()(GNode src, Galois::UserContext<GNode>& ctx) { bool* modp; if (Version == detDisjoint) { bool used; LocalState* localState = (LocalState*) ctx.getLocalState(used); modp = &localState->mod; if (used) { if (*modp) modify(src); return; } } if (Version == detDisjoint) { *modp = build<Galois::MethodFlag::ALL>(src); } else { bool mod = build<Galois::MethodFlag::ALL>(src); if (Version == detPrefix) return; else graph.getData(src, Galois::MethodFlag::WRITE); // Failsafe point if (mod) modify(src); } } }; template<bool prefix> struct OrderedProcess { typedef int tt_does_not_need_push; typedef typename Process<>::Graph Graph; typedef Graph::GraphNode GNode; Graph& graph; Process<> process; OrderedProcess(Graph& g): graph(g), process(g) { } template<typename C> void operator()(GNode src, C& ctx) { (*this)(src); } void operator()(GNode src) { if (prefix) { graph.edge_begin(src, Galois::MethodFlag::ALL); } else { if (process.build<Galois::MethodFlag::NONE>(src)) process.modify(src); } } }; template<typename Graph> struct Compare { typedef typename Graph::GraphNode GNode; Graph& graph; Compare(Graph& g): graph(g) { } bool operator()(const GNode& a, const GNode& b) const { return &graph.getData(a, Galois::MethodFlag::NONE)< &graph.getData(b, Galois::MethodFlag::NONE); } }; template<Algo algo> struct DefaultAlgo { typedef typename Process<>::Graph Graph; void operator()(Graph& graph) { #ifdef GALOIS_USE_EXP typedef Galois::WorkList::BulkSynchronousInline<> WL; #else typedef Galois::WorkList::dChunkedFIFO<256> WL; #endif switch (algo) { case nondet: Galois::for_each(graph.begin(), graph.end(), Process<>(graph), Galois::wl<WL>()); break; case detBase: Galois::for_each_det(graph.begin(), graph.end(), Process<>(graph)); break; case detPrefix: Galois::for_each_det(graph.begin(), graph.end(), Process<detPrefix>(graph), Process<>(graph)); break; case detDisjoint: Galois::for_each_det(graph.begin(), graph.end(), Process<detDisjoint>(graph)); break; case orderedBase: Galois::for_each_ordered(graph.begin(), graph.end(), Compare<Graph>(graph), OrderedProcess<true>(graph), OrderedProcess<false>(graph)); break; default: std::cerr << "Unknown algorithm" << algo << "\n"; abort(); } } }; struct PullAlgo { typedef Galois::Graph::LC_CSR_Graph<Node,void> ::with_numa_alloc<true>::type ::with_no_lockable<true>::type Graph; typedef Graph::GraphNode GNode; struct Pull { typedef int tt_does_not_need_push; typedef int tt_does_not_need_aborts; typedef Galois::InsertBag<GNode> Bag; Graph& graph; Bag& tcur; Bag& next; void operator()(GNode src, Galois::UserContext<GNode>&) { (*this)(src); } void operator()(GNode src) { Node& n = graph.getData(src, Galois::MethodFlag::NONE); MatchFlag f = MATCHED; for (Graph::edge_iterator ii = graph.edge_begin(src, Galois::MethodFlag::NONE), ei = graph.edge_end(src, Galois::MethodFlag::NONE); ii != ei; ++ii) { GNode dst = graph.getEdgeDst(ii); Node& other = graph.getData(dst, Galois::MethodFlag::NONE); if (dst >= src) continue; if (other.flag == MATCHED) { f = OTHER_MATCHED; break; } else if (other.flag == UNMATCHED) { f = UNMATCHED; } } if (f == UNMATCHED) { next.push_back(src); return; } n.pendingFlag = f; tcur.push_back(src); } }; struct Take { Graph& graph; void operator()(GNode src) { Node& n = graph.getData(src, Galois::MethodFlag::NONE); n.flag = n.pendingFlag; } }; void operator()(Graph& graph) { Galois::Statistic rounds("Rounds"); typedef Galois::InsertBag<GNode> Bag; Bag bags[3]; Bag *cur = &bags[0]; Bag *tcur = &bags[1]; Bag *next = &bags[2]; uint64_t size = graph.size(); uint64_t delta = graph.size() / 25; Graph::iterator ii = graph.begin(); Graph::iterator ei = graph.begin(); uint64_t remaining = std::min(size, delta); std::advance(ei, remaining); size -= remaining; while (ii != ei) { Pull pull = { graph, *tcur, *next }; Galois::do_all(ii, ei, pull); Take take = { graph }; Galois::do_all_local(*tcur, take); rounds += 1; while (!next->empty()) { cur->clear(); tcur->clear(); std::swap(cur, next); Pull pull = { graph, *tcur, *next }; Galois::do_all_local(*cur, pull); Galois::do_all_local(*tcur, take); rounds += 1; } ii = ei; remaining = std::min(size, delta); std::advance(ei, remaining); size -= remaining; } } }; template<typename Graph> struct is_bad { typedef typename Graph::GraphNode GNode; Graph& graph; is_bad(Graph& g): graph(g) { } bool operator()(GNode n) const { Node& me = graph.getData(n); if (me.flag == MATCHED) { for (typename Graph::edge_iterator ii = graph.edge_begin(n), ei = graph.edge_end(n); ii != ei; ++ii) { GNode dst = graph.getEdgeDst(ii); Node& data = graph.getData(dst); if (dst != n && data.flag == MATCHED) { std::cerr << "double match\n"; return true; } } } else if (me.flag == UNMATCHED) { bool ok = false; for (typename Graph::edge_iterator ii = graph.edge_begin(n), ei = graph.edge_end(n); ii != ei; ++ii) { GNode dst = graph.getEdgeDst(ii); Node& data = graph.getData(dst); if (data.flag != UNMATCHED) { ok = true; } } if (!ok) { std::cerr << "not maximal\n"; return true; } } return false; } }; template<typename Graph> struct is_matched { typedef typename Graph::GraphNode GNode; Graph& graph; is_matched(Graph& g): graph(g) { } bool operator()(const GNode& n) const { return graph.getData(n).flag == MATCHED; } }; template<typename Graph> bool verify(Graph& graph) { return Galois::ParallelSTL::find_if( graph.begin(), graph.end(), is_bad<Graph>(graph)) == graph.end(); } template<typename Algo> void run() { typedef typename Algo::Graph Graph; Algo algo; Graph graph; Galois::Graph::readGraph(graph, filename); // XXX Test if this matters Galois::preAlloc(numThreads + (graph.size() * sizeof(Node) * numThreads / 8) / Galois::Runtime::MM::pageSize); Galois::reportPageAlloc("MeminfoPre"); Galois::StatTimer T; T.start(); algo(graph); T.stop(); Galois::reportPageAlloc("MeminfoPost"); std::cout << "Cardinality of maximal independent set: " << Galois::ParallelSTL::count_if(graph.begin(), graph.end(), is_matched<Graph>(graph)) << "\n"; if (!skipVerify && !verify(graph)) { std::cerr << "verification failed\n"; assert(0 && "verification failed"); abort(); } } int main(int argc, char** argv) { Galois::StatManager statManager; LonestarStart(argc, argv, name, desc, url); switch (algo) { case serial: run<SerialAlgo>(); break; case nondet: run<DefaultAlgo<nondet> >(); break; case detBase: run<DefaultAlgo<detBase> >(); break; case detPrefix: run<DefaultAlgo<detPrefix> >(); break; case detDisjoint: run<DefaultAlgo<detDisjoint> >(); break; case orderedBase: run<DefaultAlgo<orderedBase> >(); break; case pull: run<PullAlgo>(); break; default: std::cerr << "Unknown algorithm" << algo << "\n"; abort(); } return 0; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/sssp/CMakeLists.txt
app(sssp-all SSSPall.cpp) app(sssp SSSP.cpp)
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/sssp/GraphLabAlgo.h
#ifndef APPS_SSSP_GRAPHLABALGO_H #define APPS_SSSP_GRAPHLABALGO_H #include "Galois/DomainSpecificExecutors.h" #include "Galois/Graph/OCGraph.h" #include "Galois/Graph/LCGraph.h" #include "Galois/Graph/GraphNodeBag.h" #include <boost/mpl/if.hpp> #include "SSSP.h" struct GraphLabAlgo { typedef Galois::Graph::LC_CSR_Graph<SNode,uint32_t> ::with_no_lockable<true>::type ::with_numa_alloc<true>::type InnerGraph; typedef Galois::Graph::LC_InOut_Graph<InnerGraph> Graph; typedef Graph::GraphNode GNode; std::string name() const { return "GraphLab"; } void readGraph(Graph& graph) { readInOutGraph(graph); } struct Initialize { Graph& g; Initialize(Graph& g): g(g) { } void operator()(Graph::GraphNode n) { g.getData(n).dist = DIST_INFINITY; } }; struct Program { Dist min_dist; bool changed; struct gather_type { }; typedef int tt_needs_scatter_out_edges; struct message_type { Dist dist; message_type(Dist d = DIST_INFINITY): dist(d) { } message_type& operator+=(const message_type& other) { dist = std::min(dist, other.dist); return *this; } }; void init(Graph& graph, GNode node, const message_type& msg) { min_dist = msg.dist; } void apply(Graph& graph, GNode node, const gather_type&) { changed = false; SNode& data = graph.getData(node, Galois::MethodFlag::NONE); if (data.dist > min_dist) { changed = true; data.dist = min_dist; } } bool needsScatter(Graph& graph, GNode node) { return changed; } void scatter(Graph& graph, GNode node, GNode src, GNode dst, Galois::GraphLab::Context<Graph,Program>& ctx, Graph::edge_data_reference edgeValue) { SNode& ddata = graph.getData(dst, Galois::MethodFlag::NONE); SNode& sdata = graph.getData(src, Galois::MethodFlag::NONE); Dist newDist = sdata.dist + edgeValue; if (ddata.dist > newDist) { ctx.push(dst, message_type(newDist)); } } void gather(Graph& graph, GNode node, GNode src, GNode dst, gather_type&, Graph::edge_data_reference) { } }; void operator()(Graph& graph, const GNode& source) { Galois::GraphLab::SyncEngine<Graph,Program> engine(graph, Program()); engine.signal(source, Program::message_type(0)); engine.execute(); } }; #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/sssp/SSSPall.cpp
/** Single source shortest paths -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @section Description * * Single source shortest paths. * * @author Andrew Lenharth <[email protected]> */ #include "SSSPall.h" #include "Galois/Timer.h" #include "Galois/Statistic.h" #include "Galois/Galois.h" #include "Galois/UserContext.h" #include "Galois/Graph/LCGraph.h" #include "llvm/Support/CommandLine.h" #include "Lonestar/BoilerPlate.h" #include <iostream> #include <set> namespace cll = llvm::cl; static const char* name = "Single Source Shortest Path"; static const char* desc = "Computes the shortest path from a source node to all nodes in a directed " "graph using a modified Bellman-Ford algorithm"; static const char* url = "single_source_shortest_path"; static cll::opt<std::string> filename(cll::Positional, cll::desc("<input file>"), cll::Required); static cll::opt<int> stepShift("delta", cll::desc("Shift value for the deltastep"), cll::init(10)); typedef Galois::Graph::LC_InlineEdge_Graph<SNode, uint32_t> ::with_out_of_line_lockable<true>::type ::with_compressed_node_ptr<true>::type ::with_numa_alloc<true>::type Graph; typedef Graph::GraphNode GNode; typedef UpdateRequestCommon<GNode> UpdateRequest; struct UpdateRequestIndexer : std::unary_function<UpdateRequest, unsigned int> { unsigned int operator() (const UpdateRequest& val) const { unsigned int t = val.w >> stepShift; return t; } }; Graph graph; struct process { typedef int tt_does_not_need_aborts; void operator()(UpdateRequest& req, Galois::UserContext<UpdateRequest>& lwl) { SNode& data = graph.getData(req.n,Galois::MethodFlag::NONE); // if (req.w >= data.dist) // *WLEmptyWork += 1; unsigned int v; while (req.w < (v = data.dist[req.c])) { if (__sync_bool_compare_and_swap(&data.dist[req.c], v, req.w)) { // if (v != DIST_INFINITY) // *BadWork += 1; for (Graph::edge_iterator ii = graph.edge_begin(req.n, Galois::MethodFlag::NONE), ee = graph.edge_end(req.n, Galois::MethodFlag::NONE); ii != ee; ++ii) { GNode dst = graph.getEdgeDst(ii); int d = graph.getEdgeData(ii); unsigned int newDist = req.w + d; SNode& rdata = graph.getData(dst,Galois::MethodFlag::NONE); if (newDist < rdata.dist[req.c]) lwl.push(UpdateRequest(dst, newDist, req.c)); } break; } } } }; struct reset { void operator()(GNode n) {//, Galois::UserContext<GNode>& lwl) { SNode& S = graph.getData(n, Galois::MethodFlag::NONE); for (int i = 0; i < NUM; ++i) S.dist[i] = DIST_INFINITY; } // void operator()(GNode n, Galois::UserContext<GNode>& lwl) { // operator()(n); // } }; void runBodyParallel(const GNode src[NUM], int n) { using namespace Galois::WorkList; typedef dChunkedLIFO<16> dChunk; typedef ChunkedLIFO<16> Chunk; typedef OrderedByIntegerMetric<UpdateRequestIndexer,dChunk> OBIM; Galois::StatTimer T; UpdateRequest one[NUM]; for (int i = 0; i < n; ++i) one[i] = UpdateRequest(src[i], 0, i); T.start(); Galois::for_each(&one[0], &one[n], process(), Galois::wl<OBIM>()); T.stop(); } void resetParallel() { Galois::do_all(graph.begin(), graph.end(), reset()); } int main(int argc, char **argv) { LonestarStart(argc, argv, name, desc, url); // Galois::Statistic<unsigned int> sBadWork("BadWork"); // Galois::Statistic<unsigned int> sWLEmptyWork("WLEmptyWork"); // BadWork = &sBadWork; // WLEmptyWork = &sWLEmptyWork; Galois::Graph::readGraph(graph, filename); std::cout << "Read " << graph.size() << " nodes\n"; std::cout << "Using delta-step of " << (1 << stepShift) << "\n"; std::cout << "Doing " << NUM << " at a time\n"; std::cout << "WARNING: Performance varies considerably due to -delta. Do not expect the default to be good for your graph\n"; unsigned int id = 0; for (Graph::iterator src = graph.begin(), ee = graph.end(); src != ee; ++src) { SNode& node = graph.getData(*src,Galois::MethodFlag::NONE); node.id = id++; } resetParallel(); Galois::StatTimer T("AllSourcesTimer"); T.start(); int at = 0; GNode N[NUM]; for (Graph::iterator src = graph.begin(), ee = graph.end(); src != ee; ++src) { N[at++] = *src; if (at == NUM) { runBodyParallel(N, NUM); resetParallel(); at = 0; } } if (at != 0) runBodyParallel(N, at); T.stop(); return 0; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/sssp/SSSP.h
/** Single source shortest paths -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2013, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @section Description * * Single source shortest paths. * * @author Andrew Lenharth <[email protected]> */ #ifndef APPS_SSSP_SSSP_H #define APPS_SSSP_SSSP_H #include "llvm/Support/CommandLine.h" #include <limits> #include <string> #include <sstream> #include <stdint.h> typedef unsigned int Dist; static const Dist DIST_INFINITY = std::numeric_limits<Dist>::max() - 1; template<typename GrNode> struct UpdateRequestCommon { GrNode n; Dist w; UpdateRequestCommon(const GrNode& N, Dist W): n(N), w(W) {} UpdateRequestCommon(): n(), w(0) {} bool operator>(const UpdateRequestCommon& rhs) const { if (w > rhs.w) return true; if (w < rhs.w) return false; return n > rhs.n; } bool operator<(const UpdateRequestCommon& rhs) const { if (w < rhs.w) return true; if (w > rhs.w) return false; return n < rhs.n; } bool operator!=(const UpdateRequestCommon& other) const { if (w != other.w) return true; return n != other.n; } uintptr_t getID() const { return reinterpret_cast<uintptr_t>(n); } }; struct SNode { Dist dist; }; template<typename Graph> void readInOutGraph(Graph& graph); extern llvm::cl::opt<unsigned int> memoryLimit; #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/sssp/SSSPall.h
/** Single source shortest paths -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @section Description * * Single source shortest paths. * * @author Andrew Lenharth <[email protected]> */ #ifndef SSSP_H #define SSSP_H #include <limits> #include <string> #include <sstream> #include <stdint.h> #define NUM 32 static const unsigned int DIST_INFINITY = std::numeric_limits<unsigned int>::max() - 1; template<typename GrNode> struct UpdateRequestCommon { GrNode n; unsigned int w; unsigned int c; UpdateRequestCommon(const GrNode& N, unsigned int W, unsigned int C) :n(N), w(W), c(C) {} UpdateRequestCommon() :n(), w(0), c(0) {} bool operator>(const UpdateRequestCommon& rhs) const { if (w > rhs.w) return true; if (w < rhs.w) return false; if (n > rhs.n) return true; if (n < rhs.n) return false; return c > rhs.c; } bool operator<(const UpdateRequestCommon& rhs) const { if (w < rhs.w) return true; if (w > rhs.w) return false; if (n < rhs.n) return true; if (n > rhs.n) return false; return c < rhs.c; } bool operator!=(const UpdateRequestCommon& other) const { if (w != other.w) return true; if (n != other.n) return true; return c != other.c; } uintptr_t getID() const { //return static_cast<uintptr_t>(n); return reinterpret_cast<uintptr_t>(n); } }; struct SNode { unsigned int id; unsigned int dist[NUM]; SNode(int _id = -1) : id(_id) { } }; #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/sssp/SSSP.cpp
/** Single source shortest paths -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2013, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @section Description * * Single source shortest paths. * * @author Andrew Lenharth <[email protected]> */ #include "Galois/Galois.h" #include "Galois/Accumulator.h" #include "Galois/Bag.h" #include "Galois/Statistic.h" #include "Galois/Timer.h" #include "Galois/Graph/LCGraph.h" #include "Galois/Graph/TypeTraits.h" #include "llvm/Support/CommandLine.h" #include "Lonestar/BoilerPlate.h" #include <iostream> #include <deque> #include <set> #include "SSSP.h" #include "GraphLabAlgo.h" #include "LigraAlgo.h" namespace cll = llvm::cl; static const char* name = "Single Source Shortest Path"; static const char* desc = "Computes the shortest path from a source node to all nodes in a directed " "graph using a modified chaotic iteration algorithm"; static const char* url = "single_source_shortest_path"; enum Algo { async, asyncWithCas, asyncPP, graphlab, ligra, ligraChi, serial }; static cll::opt<std::string> filename(cll::Positional, cll::desc("<input graph>"), cll::Required); static cll::opt<std::string> transposeGraphName("graphTranspose", cll::desc("Transpose of input graph")); static cll::opt<bool> symmetricGraph("symmetricGraph", cll::desc("Input graph is symmetric")); static cll::opt<unsigned int> startNode("startNode", cll::desc("Node to start search from"), cll::init(0)); static cll::opt<unsigned int> reportNode("reportNode", cll::desc("Node to report distance to"), cll::init(1)); static cll::opt<int> stepShift("delta", cll::desc("Shift value for the deltastep"), cll::init(10)); cll::opt<unsigned int> memoryLimit("memoryLimit", cll::desc("Memory limit for out-of-core algorithms (in MB)"), cll::init(~0U)); static cll::opt<Algo> algo("algo", cll::desc("Choose an algorithm:"), cll::values( clEnumValN(Algo::async, "async", "Asynchronous"), clEnumValN(Algo::asyncPP, "asyncPP", "Async, CAS, push-pull"), clEnumValN(Algo::asyncWithCas, "asyncWithCas", "Use compare-and-swap to update nodes"), clEnumValN(Algo::serial, "serial", "Serial"), clEnumValN(Algo::graphlab, "graphlab", "Use GraphLab programming model"), clEnumValN(Algo::ligraChi, "ligraChi", "Use Ligra and GraphChi programming model"), clEnumValN(Algo::ligra, "ligra", "Use Ligra programming model"), clEnumValEnd), cll::init(Algo::asyncWithCas)); static const bool trackWork = true; static Galois::Statistic* BadWork; static Galois::Statistic* WLEmptyWork; template<typename Graph> struct not_visited { Graph& g; not_visited(Graph& g): g(g) { } bool operator()(typename Graph::GraphNode n) const { return g.getData(n).dist >= DIST_INFINITY; } }; template<typename Graph, typename Enable = void> struct not_consistent { not_consistent(Graph& g) { } bool operator()(typename Graph::GraphNode n) const { return false; } }; template<typename Graph> struct not_consistent<Graph, typename std::enable_if<!Galois::Graph::is_segmented<Graph>::value>::type> { Graph& g; not_consistent(Graph& g): g(g) { } bool operator()(typename Graph::GraphNode n) const { Dist dist = g.getData(n).dist; if (dist == DIST_INFINITY) return false; for (typename Graph::edge_iterator ii = g.edge_begin(n), ee = g.edge_end(n); ii != ee; ++ii) { Dist ddist = g.getData(g.getEdgeDst(ii)).dist; Dist w = g.getEdgeData(ii); if (ddist > dist + w) { //std::cout << ddist << " " << dist + w << " " << n << " " << g.getEdgeDst(ii) << "\n"; // XXX return true; } } return false; } }; template<typename Graph> struct max_dist { Graph& g; Galois::GReduceMax<Dist>& m; max_dist(Graph& g, Galois::GReduceMax<Dist>& m): g(g), m(m) { } void operator()(typename Graph::GraphNode n) const { Dist d = g.getData(n).dist; if (d == DIST_INFINITY) return; m.update(d); } }; template<typename UpdateRequest> struct UpdateRequestIndexer: public std::unary_function<UpdateRequest, unsigned int> { unsigned int operator() (const UpdateRequest& val) const { unsigned int t = val.w >> stepShift; return t; } }; template<typename Graph> bool verify(Graph& graph, typename Graph::GraphNode source) { if (graph.getData(source).dist != 0) { std::cerr << "source has non-zero dist value\n"; return false; } namespace pstl = Galois::ParallelSTL; size_t notVisited = pstl::count_if(graph.begin(), graph.end(), not_visited<Graph>(graph)); if (notVisited) { std::cerr << notVisited << " unvisited nodes; this is an error if the graph is strongly connected\n"; } bool consistent = pstl::find_if(graph.begin(), graph.end(), not_consistent<Graph>(graph)) == graph.end(); if (!consistent) { std::cerr << "node found with incorrect distance\n"; return false; } Galois::GReduceMax<Dist> m; Galois::do_all(graph.begin(), graph.end(), max_dist<Graph>(graph, m)); std::cout << "max dist: " << m.reduce() << "\n"; return true; } template<typename Algo> void initialize(Algo& algo, typename Algo::Graph& graph, typename Algo::Graph::GraphNode& source, typename Algo::Graph::GraphNode& report) { algo.readGraph(graph); std::cout << "Read " << graph.size() << " nodes\n"; if (startNode >= graph.size() || reportNode >= graph.size()) { std::cerr << "failed to set report: " << reportNode << " or failed to set source: " << startNode << "\n"; assert(0); abort(); } typename Algo::Graph::iterator it = graph.begin(); std::advance(it, startNode); source = *it; it = graph.begin(); std::advance(it, reportNode); report = *it; } template<typename Graph> void readInOutGraph(Graph& graph) { using namespace Galois::Graph; if (symmetricGraph) { Galois::Graph::readGraph(graph, filename); } else if (transposeGraphName.size()) { Galois::Graph::readGraph(graph, filename, transposeGraphName); } else { GALOIS_DIE("Graph type not supported"); } } struct SerialAlgo { typedef Galois::Graph::LC_CSR_Graph<SNode, uint32_t> ::with_no_lockable<true>::type Graph; typedef Graph::GraphNode GNode; typedef UpdateRequestCommon<GNode> UpdateRequest; std::string name() const { return "Serial"; } void readGraph(Graph& graph) { Galois::Graph::readGraph(graph, filename); } struct Initialize { Graph& g; Initialize(Graph& g): g(g) { } void operator()(Graph::GraphNode n) { g.getData(n).dist = DIST_INFINITY; } }; void operator()(Graph& graph, const GNode src) const { std::set<UpdateRequest, std::less<UpdateRequest> > initial; UpdateRequest init(src, 0); initial.insert(init); Galois::Statistic counter("Iterations"); while (!initial.empty()) { counter += 1; UpdateRequest req = *initial.begin(); initial.erase(initial.begin()); SNode& data = graph.getData(req.n, Galois::MethodFlag::NONE); if (req.w < data.dist) { data.dist = req.w; for (Graph::edge_iterator ii = graph.edge_begin(req.n, Galois::MethodFlag::NONE), ee = graph.edge_end(req.n, Galois::MethodFlag::NONE); ii != ee; ++ii) { GNode dst = graph.getEdgeDst(ii); Dist d = graph.getEdgeData(ii); Dist newDist = req.w + d; if (newDist < graph.getData(dst, Galois::MethodFlag::NONE).dist) { initial.insert(UpdateRequest(dst, newDist)); } } } } } }; template<bool UseCas> struct AsyncAlgo { typedef SNode Node; typedef Galois::Graph::LC_InlineEdge_Graph<Node, uint32_t> ::template with_out_of_line_lockable<true>::type ::template with_compressed_node_ptr<true>::type ::template with_numa_alloc<true>::type Graph; typedef typename Graph::GraphNode GNode; typedef UpdateRequestCommon<GNode> UpdateRequest; std::string name() const { return UseCas ? "Asynchronous with CAS" : "Asynchronous"; } void readGraph(Graph& graph) { Galois::Graph::readGraph(graph, filename); } struct Initialize { Graph& g; Initialize(Graph& g): g(g) { } void operator()(typename Graph::GraphNode n) { g.getData(n, Galois::MethodFlag::NONE).dist = DIST_INFINITY; } }; template<typename Pusher> void relaxEdge(Graph& graph, Node& sdata, typename Graph::edge_iterator ii, Pusher& pusher) { GNode dst = graph.getEdgeDst(ii); Dist d = graph.getEdgeData(ii); Node& ddata = graph.getData(dst, Galois::MethodFlag::NONE); Dist newDist = sdata.dist + d; Dist oldDist; while (newDist < (oldDist = ddata.dist)) { if (!UseCas || __sync_bool_compare_and_swap(&ddata.dist, oldDist, newDist)) { if (!UseCas) ddata.dist = newDist; if (trackWork && oldDist != DIST_INFINITY) *BadWork += 1; pusher.push(UpdateRequest(dst, newDist)); break; } } } template<typename Pusher> void relaxNode(Graph& graph, UpdateRequest& req, Pusher& pusher) { const Galois::MethodFlag flag = UseCas ? Galois::MethodFlag::NONE : Galois::MethodFlag::ALL; Node& sdata = graph.getData(req.n, flag); volatile Dist* sdist = &sdata.dist; if (req.w != *sdist) { if (trackWork) *WLEmptyWork += 1; return; } for (typename Graph::edge_iterator ii = graph.edge_begin(req.n, flag), ei = graph.edge_end(req.n, flag); ii != ei; ++ii) { if (req.w != *sdist) { if (trackWork) *WLEmptyWork += 1; break; } relaxEdge(graph, sdata, ii, pusher); } } struct Process { AsyncAlgo* self; Graph& graph; Process(AsyncAlgo* s, Graph& g): self(s), graph(g) { } void operator()(UpdateRequest& req, Galois::UserContext<UpdateRequest>& ctx) { self->relaxNode(graph, req, ctx); } }; typedef Galois::InsertBag<UpdateRequest> Bag; struct InitialProcess { AsyncAlgo* self; Graph& graph; Bag& bag; Node& sdata; InitialProcess(AsyncAlgo* s, Graph& g, Bag& b, Node& d): self(s), graph(g), bag(b), sdata(d) { } void operator()(typename Graph::edge_iterator ii) { self->relaxEdge(graph, sdata, ii, bag); } }; void operator()(Graph& graph, GNode source) { using namespace Galois::WorkList; typedef dChunkedFIFO<64> Chunk; typedef OrderedByIntegerMetric<UpdateRequestIndexer<UpdateRequest>, Chunk, 10> OBIM; std::cout << "INFO: Using delta-step of " << (1 << stepShift) << "\n"; std::cout << "WARNING: Performance varies considerably due to delta parameter.\n"; std::cout << "WARNING: Do not expect the default to be good for your graph.\n"; Bag initial; graph.getData(source).dist = 0; Galois::do_all( graph.out_edges(source, Galois::MethodFlag::NONE).begin(), graph.out_edges(source, Galois::MethodFlag::NONE).end(), InitialProcess(this, graph, initial, graph.getData(source))); Galois::for_each_local(initial, Process(this, graph), Galois::wl<OBIM>()); } }; struct AsyncAlgoPP { typedef SNode Node; typedef Galois::Graph::LC_InlineEdge_Graph<Node, uint32_t> ::with_out_of_line_lockable<true>::type ::with_compressed_node_ptr<true>::type ::with_numa_alloc<true>::type Graph; typedef Graph::GraphNode GNode; typedef UpdateRequestCommon<GNode> UpdateRequest; std::string name() const { return "Asynchronous with CAS and Push and pull"; } void readGraph(Graph& graph) { Galois::Graph::readGraph(graph, filename); } struct Initialize { Graph& g; Initialize(Graph& g): g(g) { } void operator()(Graph::GraphNode n) { g.getData(n, Galois::MethodFlag::NONE).dist = DIST_INFINITY; } }; template <typename Pusher> void relaxEdge(Graph& graph, Dist& sdata, typename Graph::edge_iterator ii, Pusher& pusher) { GNode dst = graph.getEdgeDst(ii); Dist d = graph.getEdgeData(ii); Node& ddata = graph.getData(dst, Galois::MethodFlag::NONE); Dist newDist = sdata + d; Dist oldDist; if (newDist < (oldDist = ddata.dist)) { do { if (__sync_bool_compare_and_swap(&ddata.dist, oldDist, newDist)) { if (trackWork && oldDist != DIST_INFINITY) *BadWork += 1; pusher.push(UpdateRequest(dst, newDist)); break; } } while (newDist < (oldDist = ddata.dist)); } else { sdata = std::min(oldDist + d, sdata); } } struct Process { AsyncAlgoPP* self; Graph& graph; Process(AsyncAlgoPP* s, Graph& g): self(s), graph(g) { } void operator()(UpdateRequest& req, Galois::UserContext<UpdateRequest>& ctx) { const Galois::MethodFlag flag = Galois::MethodFlag::NONE; Node& sdata = graph.getData(req.n, flag); volatile Dist* psdist = &sdata.dist; Dist sdist = *psdist; if (req.w != sdist) { if (trackWork) *WLEmptyWork += 1; return; } for (Graph::edge_iterator ii = graph.edge_begin(req.n, flag), ei = graph.edge_end(req.n, flag); ii != ei; ++ii) { self->relaxEdge(graph, sdist, ii, ctx); } // //try doing a pull // Dist oldDist; // while (sdist < (oldDist = *psdist)) { // if (__sync_bool_compare_and_swap(psdist, oldDist, sdist)) { // req.w = sdist; // operator()(req, ctx); // } // } } }; typedef Galois::InsertBag<UpdateRequest> Bag; struct InitialProcess { AsyncAlgoPP* self; Graph& graph; Bag& bag; InitialProcess(AsyncAlgoPP* s, Graph& g, Bag& b): self(s), graph(g), bag(b) { } void operator()(Graph::edge_iterator ii) { Dist d = 0; self->relaxEdge(graph, d, ii, bag); } }; void operator()(Graph& graph, GNode source) { using namespace Galois::WorkList; typedef dChunkedFIFO<64> Chunk; typedef OrderedByIntegerMetric<UpdateRequestIndexer<UpdateRequest>, Chunk, 10> OBIM; std::cout << "INFO: Using delta-step of " << (1 << stepShift) << "\n"; std::cout << "WARNING: Performance varies considerably due to delta parameter.\n"; std::cout << "WARNING: Do not expect the default to be good for your graph.\n"; Bag initial; graph.getData(source).dist = 0; Galois::do_all( graph.out_edges(source, Galois::MethodFlag::NONE).begin(), graph.out_edges(source, Galois::MethodFlag::NONE).end(), InitialProcess(this, graph, initial)); Galois::for_each_local(initial, Process(this, graph), Galois::wl<OBIM>()); } }; namespace Galois { template<> struct does_not_need_aborts<AsyncAlgo<true>::Process> : public boost::true_type {}; } static_assert(Galois::does_not_need_aborts<AsyncAlgo<true>::Process>::value, "Oops"); template<typename Algo> void run(bool prealloc = true) { typedef typename Algo::Graph Graph; typedef typename Graph::GraphNode GNode; Algo algo; Graph graph; GNode source, report; initialize(algo, graph, source, report); size_t approxNodeData = graph.size() * 64; //size_t approxEdgeData = graph.sizeEdges() * sizeof(typename Graph::edge_data_type) * 2; if (prealloc) Galois::preAlloc(numThreads + approxNodeData / Galois::Runtime::MM::pageSize); Galois::reportPageAlloc("MeminfoPre"); Galois::StatTimer T; std::cout << "Running " << algo.name() << " version\n"; T.start(); Galois::do_all_local(graph, typename Algo::Initialize(graph)); algo(graph, source); T.stop(); Galois::reportPageAlloc("MeminfoPost"); Galois::Runtime::reportNumaAlloc("NumaPost"); std::cout << "Node " << reportNode << " has distance " << graph.getData(report).dist << "\n"; if (!skipVerify) { if (verify(graph, source)) { std::cout << "Verification successful.\n"; } else { std::cerr << "Verification failed.\n"; assert(0 && "Verification failed"); abort(); } } } int main(int argc, char **argv) { Galois::StatManager statManager; LonestarStart(argc, argv, name, desc, url); if (trackWork) { BadWork = new Galois::Statistic("BadWork"); WLEmptyWork = new Galois::Statistic("EmptyWork"); } Galois::StatTimer T("TotalTime"); T.start(); switch (algo) { case Algo::serial: run<SerialAlgo>(); break; case Algo::async: run<AsyncAlgo<false> >(); break; case Algo::asyncWithCas: run<AsyncAlgo<true> >(); break; case Algo::asyncPP: run<AsyncAlgoPP>(); break; #if defined(__IBMCPP__) && __IBMCPP__ <= 1210 #else case Algo::ligra: run<LigraAlgo<false> >(); break; case Algo::ligraChi: run<LigraAlgo<true> >(false); break; case Algo::graphlab: run<GraphLabAlgo>(); break; #endif default: std::cerr << "Unknown algorithm\n"; abort(); } T.stop(); if (trackWork) { delete BadWork; delete WLEmptyWork; } return 0; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/sssp/LigraAlgo.h
#ifndef APPS_SSSP_LIGRAALGO_H #define APPS_SSSP_LIGRAALGO_H #include "Galois/DomainSpecificExecutors.h" #include "Galois/Graph/OCGraph.h" #include "Galois/Graph/LCGraph.h" #include "Galois/Graph/GraphNodeBag.h" #include <boost/mpl/if.hpp> #include "SSSP.h" template<bool UseGraphChi> struct LigraAlgo: public Galois::LigraGraphChi::ChooseExecutor<UseGraphChi> { struct LNode: public SNode { bool visited; }; typedef typename Galois::Graph::LC_InlineEdge_Graph<LNode,uint32_t> ::template with_compressed_node_ptr<true>::type ::template with_no_lockable<true>::type ::template with_numa_alloc<true>::type InnerGraph; typedef typename boost::mpl::if_c<UseGraphChi, Galois::Graph::OCImmutableEdgeGraph<LNode,uint32_t>, Galois::Graph::LC_InOut_Graph<InnerGraph>>::type Graph; typedef typename Graph::GraphNode GNode; std::string name() const { return UseGraphChi ? "LigraChi" : "Ligra"; } void readGraph(Graph& graph) { readInOutGraph(graph); this->checkIfInMemoryGraph(graph, memoryLimit); } struct Initialize { Graph& graph; Initialize(Graph& g): graph(g) { } void operator()(GNode n) { LNode& data = graph.getData(n); data.dist = DIST_INFINITY; data.visited = false; } }; struct EdgeOperator { template<typename GTy> bool cond(GTy& graph, typename GTy::GraphNode) { return true; } template<typename GTy> bool operator()(GTy& graph, typename GTy::GraphNode src, typename GTy::GraphNode dst, typename GTy::edge_data_reference weight) { LNode& sdata = graph.getData(src, Galois::MethodFlag::NONE); LNode& ddata = graph.getData(dst, Galois::MethodFlag::NONE); while (true) { Dist newDist = sdata.dist + weight; Dist oldDist = ddata.dist; if (oldDist <= newDist) return false; if (__sync_bool_compare_and_swap(&ddata.dist, oldDist, newDist)) { return __sync_bool_compare_and_swap(&ddata.visited, false, true); } } return false; } }; struct ResetVisited { Graph& graph; ResetVisited(Graph& g): graph(g) { } void operator()(size_t n) { graph.getData(graph.nodeFromId(n)).visited = false; } }; void operator()(Graph& graph, const GNode& source) { Galois::Statistic roundStat("Rounds"); Galois::GraphNodeBagPair<> bags(graph.size()); graph.getData(source).dist = 0; this->outEdgeMap(memoryLimit, graph, EdgeOperator(), source, bags.next()); Galois::do_all_local(bags.next(), ResetVisited(graph)); unsigned rounds = 0; while (!bags.next().empty()) { if (++rounds == graph.size()) { std::cout << "Negative weight cycle\n"; break; } bags.swap(); this->outEdgeMap(memoryLimit, graph, EdgeOperator(), bags.cur(), bags.next(), true); Galois::do_all_local(bags.next(), ResetVisited(graph)); } roundStat += rounds + 1; } }; #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/tutorial/TorusImproved.cpp
/** Tutorial torus application -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2013, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @section Description * * Simple tutorial application. Creates a torus graph and each node increments * its neighbors data by one. This version improves {@link Torus.cpp} by * allocating the graph in parallel, which distributes the graph, and by * more carefully assigning work to threads. * * @author Donald Nguyen <[email protected]> */ #include "Galois/Galois.h" #include "Galois/Timer.h" #include "Galois/Graph/Graph.h" #include <iostream> //! Graph has int node data, void edge data and is directed typedef Galois::Graph::FirstGraph<int,void,true> Graph; //! Opaque pointer to graph node typedef Graph::GraphNode GNode; //! Increments node value of each neighbor by 1 struct IncrementNeighbors { Graph& g; IncrementNeighbors(Graph& g): g(g) { } //! Operator. Context parameter is unused in this example. void operator()(GNode n, Galois::UserContext<GNode>& ctx) { // For each outgoing edge (n, dst) for (Graph::edge_iterator ii = g.edge_begin(n), ei = g.edge_end(n); ii != ei; ++ii) { GNode dst = g.getEdgeDst(ii); int& data = g.getData(dst); // Increment node data by 1 data += 1; } } }; //! Returns true if node value equals v struct ValueEqual { Graph& g; int v; ValueEqual(Graph& g, int v): g(g), v(v) { } bool operator()(GNode n) { return g.getData(n) == v; } }; class Point2D { int v[2]; public: Point2D() { } Point2D(int x, int y) { v[0] = x; v[1] = y; } const int& at(int i) const { return v[i]; } const int& x() const { return v[0]; } const int& y() const { return v[1]; } int dim() const { return 2; } }; /** * Sort pairs according to Morton Z-Order. * * From http://en.wikipedia.org/wiki/Z-order_%28curve%29 */ struct ZOrderCompare { bool operator()(const Point2D& p1, const Point2D& p2) const { int index = 0; int x = 0; for (int k = 0; k < p1.dim(); ++k) { int y = p1.at(k) ^ p2.at(k); if (lessMsb(x, y)) { index = k; x = y; } } return p1.at(index) - p2.at(index) <= 0; } bool lessMsb(int a, int b) const { return a < b && a < (a ^ b); } }; struct CreateNodes { Graph& g; std::vector<GNode>& nodes; int height; CreateNodes(Graph& g, std::vector<GNode>& n, int h): g(g), nodes(n), height(h) { } void operator()(const Point2D& p) { GNode n = g.createNode(0); g.addNode(n); nodes[p.x() * height + p.y()] = n; } }; //! Construct a simple torus graph void constructTorus(Graph& g, int height, int width) { // Construct set of nodes int numNodes = height * width; std::vector<Point2D> points(numNodes); for (int x = 0; x < width; ++x) { for (int y = 0; y < height; ++y) { points[x*height + y] = Point2D(x, y); } } // Sort in a space-filling way std::sort(points.begin(), points.end(), ZOrderCompare()); // Using space-filling order, assign nodes and create (and allocate) them in parallel std::vector<GNode> nodes(numNodes); Galois::do_all(points.begin(), points.end(), CreateNodes(g, nodes, height)); // Add edges for (int x = 0; x < width; ++x) { for (int y = 0; y < height; ++y) { GNode c = nodes[x*height + y]; GNode n = nodes[x*height + ((y+1) % height)]; GNode s = nodes[x*height + ((y-1+height) % height)]; GNode e = nodes[((x+1) % width)*height + y]; GNode w = nodes[((x-1+width) % width)*height + y]; g.addEdge(c, n); g.addEdge(c, s); g.addEdge(c, e); g.addEdge(c, w); } } } int main(int argc, char** argv) { if (argc < 3) { std::cerr << "<num threads> <sqrt grid size>\n"; return 1; } unsigned int numThreads = atoi(argv[1]); int n = atoi(argv[2]); numThreads = Galois::setActiveThreads(numThreads); std::cout << "Using " << numThreads << " threads and " << n << " x " << n << " torus\n"; Graph graph; constructTorus(graph, n, n); Galois::Timer T; T.start(); // Unlike Galois::for_each, Galois::for_each_local initially assigns work // based on which thread created each node (Galois::for_each uses a simple // blocking of the iterator range to initialize work, but the iterator order // of a Graph is implementation-defined). Galois::for_each_local(graph, IncrementNeighbors(graph)); T.stop(); std::cout << "Elapsed time: " << T.get() << " milliseconds\n"; // Verify int count = std::count_if(graph.begin(), graph.end(), ValueEqual(graph, 4)); if (count != n * n) { std::cerr << "Expected " << n * n << " nodes with value = 4 but found " << count << " instead.\n"; return 1; } else { std::cout << "Correct!\n"; } return 0; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/tutorial/CMakeLists.txt
app(hello-world HelloWorld.cpp) app(torus Torus.cpp) app(torus-improved TorusImproved.cpp) app(sssp-simple SSSPsimple.cpp)
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/tutorial/SSSPsimple.cpp
/** Single source shortest paths -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2012, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @section Description * * Single source shortest paths. * * @author Andrew Lenharth <[email protected]> */ #include "Galois/Statistic.h" #include "Galois/Galois.h" #include "Galois/Graph/LCGraph.h" #include "llvm/Support/CommandLine.h" #include "Lonestar/BoilerPlate.h" typedef Galois::Graph::LC_Linear_Graph<unsigned int, unsigned int> Graph; typedef Graph::GraphNode GNode; typedef std::pair<unsigned, GNode> UpdateRequest; static const unsigned int DIST_INFINITY = std::numeric_limits<unsigned int>::max(); unsigned stepShift = 11; Graph graph; namespace cll = llvm::cl; static cll::opt<std::string> filename(cll::Positional, cll::desc("<input file>"), cll::Required); void relax_edge(unsigned src_data, Graph::edge_iterator ii, Galois::UserContext<UpdateRequest>& ctx) { GNode dst = graph.getEdgeDst(ii); unsigned int edge_data = graph.getEdgeData(ii); unsigned& dst_data = graph.getData(dst); unsigned int newDist = dst_data + edge_data; if (newDist < dst_data) { dst_data = newDist; ctx.push(std::make_pair(newDist, dst)); } } struct SSSP { void operator()(UpdateRequest& req, Galois::UserContext<UpdateRequest>& ctx) const { unsigned& data = graph.getData(req.second); if (req.first >= data) return; for (Graph::edge_iterator ii = graph.edge_begin(req.second), ee = graph.edge_end(req.second); ii != ee; ++ii) relax_edge(data, ii, ctx); } }; struct Init { void operator()(GNode& n, Galois::UserContext<GNode>& ctx) const { graph.getData(n) = DIST_INFINITY; } }; struct UpdateRequestIndexer: public std::unary_function<UpdateRequest, unsigned int> { unsigned int operator() (const UpdateRequest& val) const { return val.first >> stepShift; } }; int main(int argc, char **argv) { Galois::StatManager statManager; LonestarStart(argc, argv, 0,0,0); Galois::Graph::readGraph(graph, filename); Galois::for_each(graph.begin(), graph.end(), Init()); using namespace Galois::WorkList; typedef dChunkedLIFO<16> dChunk; typedef OrderedByIntegerMetric<UpdateRequestIndexer,dChunk> OBIM; Galois::StatTimer T; T.start(); graph.getData(*graph.begin()) = 0; Galois::for_each(std::make_pair(0U, *graph.begin()), SSSP(), Galois::wl<OBIM>()); T.stop(); return 0; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/tutorial/HelloWorld.cpp
/** My first Galois program -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2013, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @section Description * * My first Galois program. Prints "Hello World" in parallel. * * @author Donald Nguyen <[email protected]> */ #include "Galois/Galois.h" #include <boost/iterator/counting_iterator.hpp> #include <iostream> struct HelloWorld { void operator()(int i) { std::cout << "Hello " << i << "\n"; } }; void helloWorld(int i) { std::cout << "Hello " << i << "\n"; } int main(int argc, char** argv) { if (argc < 3) { std::cerr << "<num threads> <num of iterations>\n"; return 1; } unsigned int numThreads = atoi(argv[1]); int n = atoi(argv[2]); numThreads = Galois::setActiveThreads(numThreads); std::cout << "Using " << numThreads << " threads and " << n << " iterations\n"; std::cout << "Using a function object\n"; Galois::do_all(boost::make_counting_iterator<int>(0), boost::make_counting_iterator<int>(n), HelloWorld()); std::cout << "Using a function pointer\n"; Galois::do_all(boost::make_counting_iterator<int>(0), boost::make_counting_iterator<int>(n), helloWorld); return 0; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/tutorial/Torus.cpp
/** Tutorial torus application -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2013, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @section Description * * Simple tutorial application. Creates a torus graph and each node increments * its neighbors data by one. * * @author Donald Nguyen <[email protected]> */ #include "Galois/Galois.h" #include "Galois/Statistic.h" #include "Galois/Graph/Graph.h" #include <iostream> //! Graph has int node data, void edge data and is directed typedef Galois::Graph::FirstGraph<int,void,true> Graph; //! Opaque pointer to graph node typedef Graph::GraphNode GNode; //! Increments node value of each neighbor by 1 struct IncrementNeighbors { Graph& g; IncrementNeighbors(Graph& g): g(g) { } //! Operator. Context parameter is unused in this example. void operator()(GNode n, Galois::UserContext<GNode>& ctx) { // For each outgoing edge (n, dst) for (Graph::edge_iterator ii = g.edge_begin(n), ei = g.edge_end(n); ii != ei; ++ii) { GNode dst = g.getEdgeDst(ii); int& data = g.getData(dst); // Increment node data by 1 data += 1; } } }; //! Returns true if node value equals v struct ValueEqual { Graph& g; int v; ValueEqual(Graph& g, int v): g(g), v(v) { } bool operator()(GNode n) { return g.getData(n) == v; } }; //! Construct a simple torus graph void constructTorus(Graph& g, int height, int width) { // Construct set of nodes int numNodes = height * width; std::vector<GNode> nodes(numNodes); for (int i = 0; i < numNodes; ++i) { GNode n = g.createNode(0); g.addNode(n); nodes[i] = n; } // Add edges for (int x = 0; x < width; ++x) { for (int y = 0; y < height; ++y) { GNode c = nodes[x*height + y]; GNode n = nodes[x*height + ((y+1) % height)]; GNode s = nodes[x*height + ((y-1+height) % height)]; GNode e = nodes[((x+1) % width)*height + y]; GNode w = nodes[((x-1+width) % width)*height + y]; g.addEdge(c, n); g.addEdge(c, s); g.addEdge(c, e); g.addEdge(c, w); } } } int main(int argc, char** argv) { if (argc < 3) { std::cerr << "<num threads> <sqrt grid size>\n"; return 1; } unsigned int numThreads = atoi(argv[1]); int n = atoi(argv[2]); numThreads = Galois::setActiveThreads(numThreads); std::cout << "Using " << numThreads << " thread(s) and " << n << " x " << n << " torus\n"; Graph graph; constructTorus(graph, n, n); Galois::StatTimer T; T.start(); Galois::for_each(graph.begin(), graph.end(), IncrementNeighbors(graph)); T.stop(); std::cout << "Elapsed time: " << T.get() << " milliseconds\n"; // Verify int count = std::count_if(graph.begin(), graph.end(), ValueEqual(graph, 4)); if (count != n * n) { std::cerr << "Expected " << n * n << " nodes with value = 4 but found " << count << " instead.\n"; return 1; } else { std::cout << "Correct!\n"; } return 0; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/gmetis/Coarsening.cpp
/** GMetis -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2013, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author Xin Sui <[email protected]> * @author Nikunj Yadav <[email protected]> * @author Andrew Lenharth <[email protected]> */ #include "Metis.h" #include "Galois/Galois.h" #include "Galois/Accumulator.h" #include "Galois/Runtime/PerThreadStorage.h" #include <iostream> namespace { void assertAllMatched(GNode node, GGraph* graph) { for (auto jj = graph->edge_begin(node), eejj = graph->edge_end(node); jj != eejj; ++jj) assert(node == graph->getEdgeDst(jj) || graph->getData(graph->getEdgeDst(jj)).isMatched()); } void assertNoMatched(GGraph* graph) { for (auto nn = graph->begin(), en = graph->end(); nn != en; ++nn) assert(!graph->getData(*nn).isMatched()); } struct HEMmatch { std::pair<GNode, int> operator()(GNode node, GGraph* graph, bool tag) { GNode retval = node; // match self if nothing else int maxwgt = std::numeric_limits<int>::min(); // nume += std::distance(graph->edge_begin(node), graph->edge_end(node)); for (auto jj = graph->edge_begin(node, Galois::MethodFlag::NONE), eejj = graph->edge_end(node); jj != eejj; ++jj) { // ++checked; GNode neighbor = graph->getEdgeDst(jj); MetisNode& neighMNode = graph->getData(neighbor, Galois::MethodFlag::NONE); int edgeData = graph->getEdgeData(jj, Galois::MethodFlag::NONE); if (!neighMNode.isMatched() && neighbor != node && maxwgt < edgeData) { maxwgt = edgeData; retval = neighbor; } } return std::make_pair(retval, maxwgt);; } GNode operator()(GNode node, GGraph* graph) { return operator()(node, graph, true).first; } }; struct RMmatch { GNode operator()(GNode node, GGraph* graph) { for (auto jj = graph->edge_begin(node, Galois::MethodFlag::NONE), eejj = graph->edge_end(node); jj != eejj; ++jj) { GNode neighbor = graph->getEdgeDst(jj); if (!graph->getData(neighbor, Galois::MethodFlag::NONE).isMatched() && neighbor != node) return neighbor; } return node; //Don't actually do random, just choose first } std::pair<GNode, int> operator()(GNode node, GGraph* graph, bool tag) { return std::make_pair(operator()(node, graph), 0); } }; template<typename MatchingPolicy> struct TwoHopMatcher { MatchingPolicy matcher; GNode operator()(GNode node, GGraph* graph) { std::pair<GNode, int> retval(node, std::numeric_limits<int>::min()); for (auto jj = graph->edge_begin(node, Galois::MethodFlag::NONE), eejj = graph->edge_end(node); jj != eejj; ++jj) { GNode neighbor = graph->getEdgeDst(jj); std::pair<GNode, int> tval = matcher(neighbor, graph, true); if (tval.first != node && tval.first != neighbor && tval.second > retval.second) retval = tval; } return retval.first; } }; /* *This operator is responsible for matching. 1. There are two types of matching. Random and Heavy Edge matching 2. Random matching picks any random node above a threshold and matches the nodes. RM.h 3. Heavy Edge Matching matches the vertex which is connected by the heaviest edge. HEM.h 4. This operator can also create the multinode, i.e. the node which is created on combining two matched nodes. 5. You can enable/disable 4th by changing variantMetis::mergeMatching */ typedef Galois::InsertBag<GNode> NodeBag; typedef Galois::GReducible<unsigned, Galois::ReduceAssignWrap<std::plus<unsigned> > > Pcounter; template<typename MatchingPolicy> struct parallelMatchAndCreateNodes { MatchingPolicy matcher; GGraph *fineGGraph; GGraph *coarseGGraph; Pcounter& pc; NodeBag& noEdgeBag; bool selfMatch; parallelMatchAndCreateNodes(MetisGraph* Graph, Pcounter& pc, NodeBag& edBag, bool selfMatch) : matcher(), fineGGraph(Graph->getFinerGraph()->getGraph()), coarseGGraph(Graph->getGraph()), pc(pc), noEdgeBag(edBag), selfMatch(selfMatch) { assert(fineGGraph != coarseGGraph); } void operator()(GNode item, Galois::UserContext<GNode> &lwl) { if (fineGGraph->getData(item).isMatched()) return; if(fineGGraph->edge_begin(item, Galois::MethodFlag::NONE) == fineGGraph->edge_end(item, Galois::MethodFlag::NONE)){ noEdgeBag.push(item); return; } GNode ret; do { ret = matcher(item, fineGGraph); //lock ret, since we found it lock-free it may be matched, so try again } while (fineGGraph->getData(ret).isMatched()); //at this point both ret and item (and failed matches) are locked. //We do not leave the above loop until we both have the lock on //the node and check the matched status of the locked node. the //lock before (final) read ensures that we will see any write to matched unsigned numEdges = std::distance(fineGGraph->edge_begin(item, Galois::MethodFlag::NONE), fineGGraph->edge_end(item, Galois::MethodFlag::NONE)); //assert(numEdges == std::distance(fineGGraph->edge_begin(item), fineGGraph->edge_end(item))); GNode N; if (ret != item) { //match found numEdges += std::distance(fineGGraph->edge_begin(ret, Galois::MethodFlag::NONE), fineGGraph->edge_end(ret, Galois::MethodFlag::NONE)); //Cautious point N = coarseGGraph->createNode(numEdges, fineGGraph->getData(item).getWeight() + fineGGraph->getData(ret).getWeight(), item, ret); fineGGraph->getData(item).setMatched(); fineGGraph->getData(ret).setMatched(); fineGGraph->getData(item).setParent(N); fineGGraph->getData(ret).setParent(N); } else { //assertAllMatched(item, fineGGraph); //Cautious point //no match if (selfMatch) { pc.update(1); N = coarseGGraph->createNode(numEdges, fineGGraph->getData(item).getWeight(), item); fineGGraph->getData(item).setMatched(); fineGGraph->getData(item).setParent(N); } } } }; /* * This operator is responsible for doing a union find of the edges * between matched nodes and populate the edges in the coarser graph * node. */ struct parallelPopulateEdges { typedef int tt_does_not_need_push; typedef int tt_needs_per_iter_alloc; GGraph *coarseGGraph; GGraph *fineGGraph; parallelPopulateEdges(MetisGraph *Graph) :coarseGGraph(Graph->getGraph()), fineGGraph(Graph->getFinerGraph()->getGraph()) { assert(fineGGraph != coarseGGraph); } template<typename Context> void goSort(GNode node, Context& lwl) { // std::cout << 'p'; //fineGGraph is read only in this loop, so skip locks MetisNode &nodeData = coarseGGraph->getData(node, Galois::MethodFlag::NONE); typedef std::deque<std::pair<GNode, unsigned>, Galois::PerIterAllocTy::rebind<std::pair<GNode,unsigned> >::other> GD; //copy and translate all edges GD edges(GD::allocator_type(lwl.getPerIterAlloc())); for (unsigned x = 0; x < nodeData.numChildren(); ++x) for (auto ii = fineGGraph->edge_begin(nodeData.getChild(x), Galois::MethodFlag::NONE), ee = fineGGraph->edge_end(nodeData.getChild(x)); ii != ee; ++ii) { GNode dst = fineGGraph->getEdgeDst(ii); GNode p = fineGGraph->getData(dst, Galois::MethodFlag::NONE).getParent(); edges.emplace_back(p, fineGGraph->getEdgeData(ii, Galois::MethodFlag::NONE)); } //slightly faster not ordering by edge weight std::sort(edges.begin(), edges.end(), [] (const std::pair<GNode, unsigned>& lhs, const std::pair<GNode, unsigned>& rhs) { return lhs.first < rhs.first; } ); //insert edges for (auto pp = edges.begin(), ep = edges.end(); pp != ep;) { GNode dst = pp->first; unsigned sum = pp->second; ++pp; if (node != dst) { //no self edges while (pp != ep && pp->first == dst) { sum += pp->second; ++pp; } coarseGGraph->addEdgeWithoutCheck(node, dst, Galois::MethodFlag::NONE, sum); } } // assert(e); //nodeData.setNumEdges(e); } template<typename Context> void operator()(GNode node, Context& lwl) { // MetisNode &nodeData = coarseGGraph->getData(node, Galois::MethodFlag::NONE); // if (std::distance(fineGGraph->edge_begin(nodeData.getChild(0), Galois::MethodFlag::NONE), // fineGGraph->edge_begin(nodeData.getChild(0), Galois::MethodFlag::NONE)) // < 256) // goSort(node,lwl); // else // goHM(node,lwl); goSort(node, lwl); //goHeap(node,lwl); } }; struct HighDegreeIndexer: public std::unary_function<GNode, unsigned int> { static GGraph* indexgraph; unsigned int operator()(const GNode& val) const { return indexgraph->getData(val, Galois::MethodFlag::NONE).isFailedMatch() ? std::numeric_limits<unsigned int>::max() : (std::numeric_limits<unsigned int>::max() - ((std::distance(indexgraph->edge_begin(val, Galois::MethodFlag::NONE), indexgraph->edge_end(val, Galois::MethodFlag::NONE))) >> 2)); } }; GGraph* HighDegreeIndexer::indexgraph = 0; struct LowDegreeIndexer: public std::unary_function<GNode, unsigned int> { unsigned int operator()(const GNode& val) const { unsigned x =std::distance(HighDegreeIndexer::indexgraph->edge_begin(val, Galois::MethodFlag::NONE), HighDegreeIndexer::indexgraph->edge_end(val, Galois::MethodFlag::NONE)); return x; // >> 2; // int targetlevel = 0; // while (x >>= 1) ++targetlevel; // return targetlevel; } }; struct WeightIndexer: public std::unary_function<GNode, int> { int operator()(const GNode& val) const { return HighDegreeIndexer::indexgraph->getData(val, Galois::MethodFlag::NONE).getWeight(); } }; unsigned minRuns(unsigned coarsenTo, unsigned size) { unsigned num = 0; while (coarsenTo < size) { ++num; size /= 2; } return num; } unsigned fixupLoners(NodeBag& b, GGraph* coarseGGraph, GGraph* fineGGraph) { unsigned count = 0; auto ii = b.begin(), ee = b.end(); while (ii != ee) { auto i2 = ii; ++i2; if (i2 != ee) { GNode N = coarseGGraph->createNode(0, fineGGraph->getData(*ii).getWeight() + fineGGraph->getData(*i2).getWeight(), *ii, *i2); fineGGraph->getData(*ii).setMatched(); fineGGraph->getData(*i2).setMatched(); fineGGraph->getData(*ii).setParent(N); fineGGraph->getData(*i2).setParent(N); ++ii; ++count; } else { GNode N = coarseGGraph->createNode(0, fineGGraph->getData(*ii).getWeight(), *ii); fineGGraph->getData(*ii).setMatched(); fineGGraph->getData(*ii).setParent(N); } ++ii; } return count; } unsigned findMatching(MetisGraph* coarseMetisGraph, bool useRM, bool use2Hop, bool verbose) { MetisGraph* fineMetisGraph = coarseMetisGraph->getFinerGraph(); /* * Different worklist versions tried, dChunkedFIFO 256 works best with LC_MORPH_graph. * Another good type would be Lazy Iter. */ //typedef Galois::WorkList::ChunkedLIFO<64, GNode> WL; //typedef Galois::WorkList::LazyIter<decltype(fineGGraph->local_begin()),false> WL; NodeBag bagOfLoners; Pcounter pc; bool useOBIM = true; typedef decltype(fineMetisGraph->getGraph()->local_begin()) ITY; typedef Galois::WorkList::StableIterator<ITY, true> WL; //typedef Galois::WorkList::Random<> WL; if(useRM) { parallelMatchAndCreateNodes<RMmatch> pRM(coarseMetisGraph, pc, bagOfLoners, !use2Hop); Galois::for_each_local(*fineMetisGraph->getGraph(), pRM, Galois::loopname("match"), Galois::wl<WL>()); } else { //FIXME: use obim for SHEM matching typedef Galois::WorkList::dChunkedLIFO<16> Chunk; typedef Galois::WorkList::OrderedByIntegerMetric<WeightIndexer, Chunk> pW; typedef Galois::WorkList::OrderedByIntegerMetric<LowDegreeIndexer, Chunk> pLD; typedef Galois::WorkList::OrderedByIntegerMetric<HighDegreeIndexer, Chunk> pHD; HighDegreeIndexer::indexgraph = fineMetisGraph->getGraph(); parallelMatchAndCreateNodes<HEMmatch> pHEM(coarseMetisGraph, pc, bagOfLoners, !use2Hop); if (useOBIM) Galois::for_each_local(*fineMetisGraph->getGraph(), pHEM, Galois::loopname("match"), Galois::wl<pLD>()); else Galois::for_each_local(*fineMetisGraph->getGraph(), pHEM, Galois::loopname("match"), Galois::wl<WL>()); } unsigned c = fixupLoners(bagOfLoners, coarseMetisGraph->getGraph(), fineMetisGraph->getGraph()); if (verbose && c) std::cout << "\n\tLone Matches " << c; if (use2Hop) { typedef Galois::WorkList::dChunkedLIFO<16> Chunk; typedef Galois::WorkList::OrderedByIntegerMetric<WeightIndexer, Chunk> pW; typedef Galois::WorkList::OrderedByIntegerMetric<LowDegreeIndexer, Chunk> pLD; typedef Galois::WorkList::OrderedByIntegerMetric<HighDegreeIndexer, Chunk> pHD; HighDegreeIndexer::indexgraph = fineMetisGraph->getGraph(); Pcounter pc2; parallelMatchAndCreateNodes<TwoHopMatcher<HEMmatch> > p2HEM(coarseMetisGraph, pc2, bagOfLoners, true); if (useOBIM) Galois::for_each_local(*fineMetisGraph->getGraph(), p2HEM, Galois::loopname("match"), Galois::wl<pLD>()); else Galois::for_each_local(*fineMetisGraph->getGraph(), p2HEM, Galois::loopname("match"), Galois::wl<WL>()); return pc2.reduce(); } return pc.reduce(); } void createCoarseEdges(MetisGraph *coarseMetisGraph) { MetisGraph* fineMetisGraph = coarseMetisGraph->getFinerGraph(); GGraph* fineGGraph = fineMetisGraph->getGraph(); typedef Galois::WorkList::StableIterator<decltype(fineGGraph->local_begin()), true> WL; parallelPopulateEdges pPE(coarseMetisGraph); Galois::for_each_local(*coarseMetisGraph->getGraph(), pPE, Galois::loopname("popedge"), Galois::wl<WL>()); } MetisGraph* coarsenOnce(MetisGraph *fineMetisGraph, unsigned& rem, bool useRM, bool with2Hop, bool verbose) { MetisGraph *coarseMetisGraph = new MetisGraph(fineMetisGraph); Galois::Timer t, t2; if (verbose) t.start(); rem = findMatching(coarseMetisGraph, useRM, with2Hop, verbose); if (verbose) { t.stop(); std::cout << "\n\tTime Matching " << t.get() << "\n"; t2.start(); } createCoarseEdges(coarseMetisGraph); if (verbose) { t2.stop(); std::cout << "\tTime Creating " << t2.get() << "\n"; } return coarseMetisGraph; } } // anon namespace MetisGraph* coarsen(MetisGraph* fineMetisGraph, unsigned coarsenTo, bool verbose) { MetisGraph* coarseGraph = fineMetisGraph; unsigned size = std::distance(fineMetisGraph->getGraph()->begin(), fineMetisGraph->getGraph()->end()); unsigned iterNum = 0; bool with2Hop = false; unsigned stat; while (true) {//overflow if (verbose) { std::cout << "Coarsening " << iterNum << "\t"; stat = graphStat(coarseGraph->getGraph()); } unsigned rem = 0; coarseGraph = coarsenOnce(coarseGraph, rem, false, with2Hop, verbose); unsigned newSize = size / 2 + rem / 2; if (verbose) { std::cout << "\tTO\t"; unsigned stat2 = graphStat(coarseGraph->getGraph()); std::cout << "\n\tRatio " << (double)stat2 / (double)stat << " REM " << rem << " new size " << newSize << "\n"; } if (size * 3 < newSize * 4) { with2Hop = true; if (verbose) std::cout << "** Enabling 2 hop matching\n"; } else { with2Hop = false; } size = newSize; if (newSize * 4 < coarsenTo) { //be more exact near the end size = std::distance(coarseGraph->getGraph()->begin(), coarseGraph->getGraph()->end()); if (size < coarsenTo) break; } ++iterNum; } return coarseGraph; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/gmetis/GraphReader.h
/* @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author Nikunj Yadav [email protected] */ #ifndef GRAPHREADER_H_ #define GRAPHREADER_H_ #include <fstream> #include <vector> using namespace std; typedef Galois::Graph::LC_CSR_Graph<int, unsigned int> InputGraph; typedef Galois::Graph::LC_CSR_Graph<int, unsigned int>::GraphNode InputGNode; while (true) { int index = strtol(items, &remaining,10) - 1; if(index < 0) break; items = remaining; GNode n2 = nodes[index]; if(n1==n2){ continue; } graph->addEdge(n1, n2, Galois::MethodFlag::ALL, 1); graph->getData(n1).setEdgeWeight(graph->getData(n1).getEdgeWeight() + 1); graph->getData(n1).setNumEdges(graph->getData(n1).getNumEdges() + 1); countEdges++; } } parallelMakeNodes(GGraph *g,vector <GNode> &gn,InputGraph *in,Galois::GAccumulator<int> &numNodes): graph(g),inputGraph(in),gnodes(gn),pnumNodes(numNodes) {} void operator()(InputGNode node,Galois::UserContext<InputGNode> &ctx) { int id = inputGraph->getData(node); GNode item = graph->createNode(100,1); // FIXME: edge num // graph->addNode(item); gnodes[id]=item; pnumNodes+=1; } }; struct parallelMakeEdges { GGraph *graph; InputGraph *inputGraph; vector <GNode> &gnodes; bool weighted; bool directed; Galois::GAccumulator<int> &pnumEdges; parallelMakeEdges(GGraph *g,vector <GNode> &gn,InputGraph *in,Galois::GAccumulator<int> &numE,bool w=false,bool dir = true) :graph(g),inputGraph(in),gnodes(gn),pnumEdges(numE) { weighted = w; directed = dir; } void operator()(InputGNode inNode,Galois::UserContext<InputGNode> &ctx) { int nodeId = inputGraph->getData(inNode); GNode node = gnodes[nodeId]; MetisNode& nodeData = graph->getData(node); for (InputGraph::edge_iterator jj = inputGraph->edge_begin(inNode), eejj = inputGraph->edge_end(inNode); jj != eejj; ++jj) { InputGNode inNeighbor = inputGraph->getEdgeDst(jj); if(inNode == inNeighbor) continue; int neighId = inputGraph->getData(inNeighbor); int weight = 1; if(weighted){ weight = inputGraph->getEdgeData(jj); } graph->addEdge(node, gnodes[neighId], Galois::MethodFlag::ALL, weight); nodeData.setNumEdges(nodeData.getNumEdges() + 1); nodeData.setEdgeWeight(nodeData.getEdgeWeight() + weight); /*if(!directed){ graph->getEdgeData(graph->addEdge(node, gnodes[neighId])) = weight;// nodeData.incNumEdges(); nodeData.addEdgeWeight(weight); }else{ graph->getEdgeData(graph->addEdge(node, gnodes[neighId])) = weight; graph->getEdgeData(graph->addEdge(gnodes[neighId], node)) = weight; }*/ pnumEdges+=1; } } }; void readGraph(MetisGraph* metisGraph, const char* filename, bool weighted = false, bool directed = true){ InputGraph inputGraph; Galois::Graph::readGraph(inputGraph, filename); cout<<"start to transfer data to GGraph"<<endl; int id = 0; for (InputGraph::iterator ii = inputGraph.begin(), ee = inputGraph.end(); ii != ee; ++ii) { InputGNode node = *ii; inputGraph.getData(node)=id++; } GGraph* graph = metisGraph->getGraph(); vector<GNode> gnodes(inputGraph.size()); id = 0; /*for(uint64_t i=0;i<inputGraph.size();i++){ GNode node = graph->createNode(MetisNode(id, 1)); graph->addNode(node); gnodes[id++] = node; }*/ typedef Galois::WorkList::dChunkedFIFO<256> WL; Galois::GAccumulator<int> pnumNodes; Galois::GAccumulator<int> pnumEdges; Galois::Timer t; t.start(); Galois::for_each<WL>(inputGraph.begin(),inputGraph.end(),parallelMakeNodes(graph,gnodes,&inputGraph,pnumNodes),"NodesLoad"); t.stop(); cout<<t.get()<<" ms "<<endl; t.start(); Galois::for_each<WL>(inputGraph.begin(),inputGraph.end(),parallelMakeEdges(graph,gnodes,&inputGraph,pnumEdges,weighted,true),"EdgesLoad"); t.stop(); cout<<t.get()<<" ms "<<endl; /* Galois::Timer t; t.start(); Galois::for_each_local<WL>(inputGraph,parallelMakeNodes(graph,gnodes,&inputGraph,pnumNodes),"NodesLoad"); t.stop(); cout<<t.get()<<" ms "<<endl; t.start(); Galois::for_each_local<WL>(inputGraph,parallelMakeEdges(graph,gnodes,&inputGraph,pnumEdges,weighted,true),"EdgesLoad"); t.stop(); cout<<t.get()<<" ms "<<endl; */ int numNodes = pnumNodes.reduce(); int numEdges = pnumEdges.reduce(); // metisGraph->setNumNodes(numNodes); // metisGraph->setNumEdges(numEdges/2); cout<<"Done Reading Graph "; cout<<"numNodes: "<<numNodes<<"|numEdges: "<< numEdges/2 <<endl; } #endif /* GRAPHREADER_H_ */
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/gmetis/CMakeLists.txt
app(gmetis)
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/gmetis/Partitioning.cpp
/** GMetis -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2013, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author Xin Sui <[email protected]> * @author Nikunj Yadav <[email protected]> * @author Andrew Lenharth <[email protected]> */ #include "Galois/Galois.h" #include "Galois/Statistic.h" #include "Metis.h" #include <set> #include <cstdlib> #include <iostream> const bool multiSeed = true; namespace { //gain of moving n from it's current part to new part int gain_limited(GGraph& g, GNode n, unsigned newpart, Galois::MethodFlag flag) { int retval = 0; unsigned nPart = g.getData(n,flag).getPart(); for (auto ii = g.edge_begin(n,flag), ee =g.edge_end(n,flag); ii != ee; ++ii) { GNode neigh = g.getEdgeDst(ii); if (g.getData(neigh,flag).getPart() == nPart) retval -= g.getEdgeData(ii,flag); else if (g.getData(neigh,flag).getPart() == newpart) retval += g.getEdgeData(ii,flag); } return retval; } GNode findSeed(GGraph& g, unsigned partNum, int partWeight, Galois::MethodFlag flag) { //pick a seed int rWeight = (int)(drand48()*(partWeight)); GNode seed; for (auto ii = g.begin(), ee = g.end(); ii != ee; ++ii) { if (g.getData(*ii, flag).getPart() == partNum) { seed = *ii; rWeight -= g.getData(*ii, flag).getWeight(); if(rWeight <0) return *ii; } } return seed; } struct bisect_GGP { partInfo operator()(GGraph& g, partInfo& oldPart, std::pair<unsigned, unsigned> ratio) { partInfo newPart = oldPart.split(); std::deque<GNode> boundary; unsigned& newWeight = newPart.partWeight = 0; unsigned targetWeight = oldPart.partWeight * ratio.second / (ratio.first + ratio.second); auto flag = Galois::MethodFlag::NONE; do { boundary.push_back(findSeed(g, oldPart.partNum, oldPart.partWeight, flag)); //grow partition while (newWeight < targetWeight && !boundary.empty()) { GNode n = boundary.front(); boundary.pop_front(); if (g.getData(n, flag).getPart() == newPart.partNum) continue; newWeight += g.getData(n, flag).getWeight(); g.getData(n, flag).setPart(newPart.partNum); for (auto ii = g.edge_begin(n, flag), ee = g.edge_end(n, flag); ii != ee; ++ii) if (g.getData(g.getEdgeDst(ii), flag).getPart() == oldPart.partNum) boundary.push_back(g.getEdgeDst(ii)); } } while (newWeight < targetWeight && multiSeed); oldPart.partWeight -= newWeight; return newPart; } }; struct bisect_GGGP { partInfo operator()(GGraph& g, partInfo& oldPart, std::pair<unsigned, unsigned> ratio) { partInfo newPart = oldPart.split(); std::map<GNode, int> gains; std::map<int, std::set<GNode>> boundary; unsigned& newWeight = newPart.partWeight = 0; unsigned targetWeight = oldPart.partWeight * ratio.second / (ratio.first + ratio.second); //pick a seed auto flag = Galois::MethodFlag::NONE; do { boundary[0].insert(findSeed(g, oldPart.partNum, oldPart.partWeight, flag)); //grow partition while (newWeight < targetWeight && !boundary.empty()) { auto bi = boundary.rbegin(); GNode n = *bi->second.begin(); bi->second.erase(bi->second.begin()); if (bi->second.empty()) boundary.erase(bi->first); if (g.getData(n, flag).getPart() == newPart.partNum) continue; newWeight += g.getData(n, flag).getWeight(); g.getData(n, flag).setPart(newPart.partNum); for (auto ii = g.edge_begin(n, flag), ee = g.edge_end(n, flag); ii != ee; ++ii) { GNode dst = g.getEdgeDst(ii); auto gi = gains.find(dst); if (gi != gains.end()) { //update boundary[gi->second].erase(dst); if (boundary[gi->second].empty()) boundary.erase(gi->second); gains.erase(dst); } if (g.getData(dst, flag).getPart() == oldPart.partNum) { int newgain = gains[dst] = gain_limited(g, dst, newPart.partNum, flag); boundary[newgain].insert(dst); } } } } while (newWeight < targetWeight && multiSeed); oldPart.partWeight -= newWeight; return newPart; } }; template<typename bisector> struct parallelBisect { unsigned totalWeight; unsigned nparts; GGraph* graph; bisector bisect; std::vector<partInfo>& parts; parallelBisect(MetisGraph* mg, unsigned parts, std::vector<partInfo>& pb, bisector b = bisector()) :totalWeight(mg->getTotalWeight()), nparts(parts), graph(mg->getGraph()), bisect(b), parts(pb) {} void operator()(partInfo* item, Galois::UserContext<partInfo*> &cnx) { if (item->splitID() >= nparts) //when to stop return; std::pair<unsigned, unsigned> ratio = item->splitRatio(nparts); //std::cout << "Splitting " << item->partNum << ":" << item->partMask << " L " << ratio.first << " R " << ratio.second << "\n"; partInfo newPart = bisect(*graph, *item, ratio); //std::cout << "Result " << item->partNum << " " << newPart.partNum << "\n"; parts[newPart.partNum] = newPart; cnx.push(&parts[newPart.partNum]); cnx.push(item); } }; struct initPart { GGraph& g; initPart(GGraph& _g): g(_g) {} void operator()(GNode item) { g.getData(item, Galois::MethodFlag::NONE).initRefine(0,true); } }; } //anon namespace std::vector<partInfo> partition(MetisGraph* mcg, unsigned numPartitions, InitialPartMode partMode) { std::vector<partInfo> parts(numPartitions); parts[0] = partInfo(mcg->getTotalWeight()); Galois::do_all_local(*mcg->getGraph(), initPart(*mcg->getGraph())); switch (partMode) { case GGP: std::cout <<"\n Sarting initial partitioning using GGP:\n"; Galois::for_each(&parts[0], parallelBisect<bisect_GGP>(mcg, numPartitions, parts), Galois::wl<Galois::WorkList::ChunkedLIFO<1>>()); break; case GGGP: std::cout <<"\n Sarting initial partitioning using GGGP:\n"; Galois::for_each(&parts[0], parallelBisect<bisect_GGGP>(mcg, numPartitions, parts), Galois::wl<Galois::WorkList::ChunkedLIFO<1>>()); break; default: abort(); } printPartStats(parts); #if 0 if (!multiSeed) { printPartStats(parts); unsigned maxWeight = 1.01 * mcg->getTotalWeight() / numPartitions; balance(mcg, parts, maxWeight); } #endif static_assert(multiSeed, "not yet implemented"); return parts; } namespace { int computeEdgeCut(GGraph& g) { int cuts=0; for (auto nn = g.begin(), en = g.end(); nn != en; ++nn) { unsigned gPart = g.getData(*nn).getPart(); for (auto ii = g.edge_begin(*nn), ee = g.edge_end(*nn); ii != ee; ++ii) { auto& m = g.getData(g.getEdgeDst(ii)); if (m.getPart() != gPart) { cuts += g.getEdgeData(ii); } } } return cuts/2; } int edgeCount(GGraph& g) { int count=0; for (auto nn = g.begin(), en = g.end(); nn != en; ++nn) { for (auto ii = g.edge_begin(*nn), ee = g.edge_end(*nn); ii != ee; ++ii) count += g.getEdgeData(ii); } return count/2; } } std::vector<partInfo> BisectAll(MetisGraph* mcg, unsigned numPartitions, unsigned maxSize) { std::cout <<"\n Sarting initial partitioning using MGGGP:\n"; auto flag = Galois::MethodFlag::NONE; GGraph& g = *mcg->getGraph(); int bestCut = edgeCount(g); std::map<GNode, int> bestParts; std::vector<partInfo> bestPartInfos(numPartitions); for(int nbTry =0; nbTry <20; nbTry ++){ std::vector<partInfo> partInfos(numPartitions); std::vector<std::map<int, std::set<GNode>>> boundary(numPartitions); std::map<int, std::set<int>> partitions; for(GGraph::iterator ii = g.begin(),ee = g.end();ii!=ee;ii++) g.getData(*ii).setPart(numPartitions+1); auto seedIter = g.begin(); int k =0; //find one seed for each partition and do initialization for (unsigned int i =0; i<numPartitions; i++){ int seed = (int)(drand48()*(mcg->getNumNodes())) +1; bool goodseed = true; while(seed--) if(++seedIter== g.end())seedIter = g.begin(); GNode n = *seedIter; for(unsigned int j=0; j<i && k <50; j++){ goodseed = goodseed && (*boundary[j][0].begin() != n); for (auto ii = g.edge_begin(n, flag), ee = g.edge_end(n, flag); ii != ee; ++ii) goodseed = goodseed && (*boundary[j][0].begin() != g.getEdgeDst(ii)); } if (!goodseed){ k++; i--; continue; } partInfos[i] = partInfo(i, 0, 0); boundary[i][0].insert(n); partitions[0].insert(i); } auto beg = g.begin(); while(!partitions.empty()){ //find the next partition to improove auto bb = partitions.begin(); int partToMod = *bb->second.begin(); bb->second.erase(bb->second.begin()); if (bb->second.empty()) partitions.erase(bb->first); //find the node to add to the partition GNode n = *g.begin(); do{ if(boundary[partToMod].empty()) break; auto bi = boundary[partToMod].rbegin(); n = *bi->second.begin(); bi->second.erase(bi->second.begin()); if (bi->second.empty()) boundary[partToMod].erase(bi->first); }while(g.getData(n, flag).getPart() <numPartitions && !boundary[partToMod].empty()); if(g.getData(n, flag).getPart() <numPartitions && boundary[partToMod].empty()){ GGraph::iterator ii = beg, ee = g.end(); for(;ii!=ee;ii++) if(g.getData(*ii).getPart() == numPartitions+1) break; if (ii == ee) break; else n = *(beg=ii); } //add the node partInfos[partToMod].partWeight += g.getData(n, flag).getWeight(); partitions[partInfos[partToMod].partWeight].insert(partToMod); g.getData(n, flag).setPart(partToMod); for (auto ii = g.edge_begin(n, flag), ee = g.edge_end(n, flag); ii != ee; ++ii) { GNode dst = g.getEdgeDst(ii); int newgain= gain_limited(g, dst, partToMod, flag); boundary[partToMod][newgain].insert(dst); } } //decides if this partition is the nez best one int newCut = computeEdgeCut(g); if(newCut<bestCut){ bestCut = newCut; for(GGraph::iterator ii = g.begin(),ee = g.end();ii!=ee;ii++) bestParts[*ii] = g.getData(*ii,flag).getPart(); for (unsigned int i =0; i<numPartitions; i++) bestPartInfos[i] = partInfos[i]; } } for(GGraph::iterator ii = g.begin(),ee = g.end();ii!=ee;ii++) g.getData(*ii,flag).setPart(bestParts[*ii]); return bestPartInfos; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/gmetis/Refine.cpp
/** GMetis -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2013, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author Xin Sui <[email protected]> * @author Nikunj Yadav <[email protected]> * @author Andrew Lenharth <[email protected]> */ #include "Galois/Galois.h" #include "Galois/Accumulator.h" #include "Galois/Statistic.h" #include "Metis.h" #include <set> #include <iostream> namespace { struct gainIndexer : public std::unary_function<GNode, int> { static GGraph* g; int operator()(GNode n) { int retval = 0; Galois::MethodFlag flag = Galois::NONE; unsigned int nPart = g->getData(n, flag).getPart(); for (auto ii = g->edge_begin(n, flag), ee = g->edge_end(n); ii != ee; ++ii) { GNode neigh = g->getEdgeDst(ii); if (g->getData(neigh, flag).getPart() == nPart) retval -= g->getEdgeData(ii, flag); else retval += g->getEdgeData(ii, flag); } return -retval / 16; } }; GGraph* gainIndexer::g; bool isBoundary(GGraph& g, GNode n) { unsigned int nPart = g.getData(n).getPart(); for (auto ii = g.edge_begin(n), ee =g.edge_end(n); ii != ee; ++ii) if (g.getData(g.getEdgeDst(ii)).getPart() != nPart) return true; return false; } //This is only used on the terminal graph (find graph) struct findBoundary { Galois::InsertBag<GNode>& b; GGraph& g; findBoundary(Galois::InsertBag<GNode>& _b, GGraph& _g) : b(_b), g(_g) {} void operator()(GNode n) { auto& cn = g.getData(n, Galois::MethodFlag::NONE); if (cn.getmaybeBoundary()) cn.setmaybeBoundary(isBoundary(g,n)); if (cn.getmaybeBoundary()) b.push(n); } }; //this is used on the coarse graph to project to the fine graph struct findBoundaryAndProject { Galois::InsertBag<GNode>& b; GGraph& cg; GGraph& fg; findBoundaryAndProject(Galois::InsertBag<GNode>& _b, GGraph& _cg, GGraph& _fg) :b(_b), cg(_cg), fg(_fg) {} void operator()(GNode n) { auto& cn = cg.getData(n, Galois::MethodFlag::NONE); if (cn.getmaybeBoundary()) cn.setmaybeBoundary(isBoundary(cg,n)); //project part and maybe boundary //unsigned part = cn.getPart(); for (unsigned x = 0; x < cn.numChildren(); ++x) { fg.getData(cn.getChild(x), Galois::MethodFlag::NONE).initRefine(cn.getPart(), cn.getmaybeBoundary()); } if (cn.getmaybeBoundary()) b.push(n); } }; template<bool balance> struct refine_BKL2 { unsigned meanSize; unsigned minSize; unsigned maxSize; GGraph& cg; GGraph* fg; std::vector<partInfo>& parts; typedef int tt_needs_per_iter_alloc; refine_BKL2(unsigned mis, unsigned mas, GGraph& _cg, GGraph* _fg, std::vector<partInfo>& _p) : minSize(mis), maxSize(mas), cg(_cg), fg(_fg), parts(_p) {} //Find the partition n is most connected to template<typename Context> unsigned pickPartitionEC(GNode n, Context& cnx) { std::vector<unsigned, Galois::PerIterAllocTy::rebind<unsigned>::other> edges(parts.size(), 0, cnx.getPerIterAlloc()); unsigned P = cg.getData(n).getPart(); for (auto ii = cg.edge_begin(n), ee = cg.edge_end(n); ii != ee; ++ii) { GNode neigh = cg.getEdgeDst(ii); auto& nd = cg.getData(neigh); if (parts[nd.getPart()].partWeight < maxSize || nd.getPart() == P) edges[nd.getPart()] += cg.getEdgeData(ii); } return std::distance(edges.begin(), std::max_element(edges.begin(), edges.end())); } //Find the smallest partition n is connected to template<typename Context> unsigned pickPartitionMP(GNode n, Context& cnx) { unsigned P = cg.getData(n).getPart(); unsigned W = parts[P].partWeight; std::vector<unsigned, Galois::PerIterAllocTy::rebind<unsigned>::other> edges(parts.size(), ~0, cnx.getPerIterAlloc()); edges[P] = W; W = (double)W * 0.9; for (auto ii = cg.edge_begin(n), ee = cg.edge_end(n); ii != ee; ++ii) { GNode neigh = cg.getEdgeDst(ii); auto& nd = cg.getData(neigh); if (parts[nd.getPart()].partWeight < W) edges[nd.getPart()] = parts[nd.getPart()].partWeight; } return std::distance(edges.begin(), std::min_element(edges.begin(), edges.end())); } template<typename Context> void operator()(GNode n, Context& cnx) { auto& nd = cg.getData(n); unsigned curpart = nd.getPart(); unsigned newpart = balance ? pickPartitionMP(n, cnx) : pickPartitionEC(n, cnx); if(parts[curpart].partWeight < minSize) return; if (curpart != newpart) { nd.setPart(newpart); __sync_fetch_and_sub(&parts[curpart].partWeight, nd.getWeight()); __sync_fetch_and_add(&parts[newpart].partWeight, nd.getWeight()); for (auto ii = cg.edge_begin(n), ee = cg.edge_end(n); ii != ee; ++ii) { GNode neigh = cg.getEdgeDst(ii); auto& ned = cg.getData(neigh); if (ned.getPart() != newpart && !ned.getmaybeBoundary()) { ned.setmaybeBoundary(true); if (fg) for (unsigned x = 0; x < ned.numChildren(); ++x) fg->getData(ned.getChild(x), Galois::MethodFlag::NONE).setmaybeBoundary(true); } //if (ned.getPart() != newpart) //cnx.push(neigh); } if (fg) for (unsigned x = 0; x < nd.numChildren(); ++x) fg->getData(nd.getChild(x), Galois::MethodFlag::NONE).setPart(newpart); } } static void go(unsigned mins, unsigned maxs, GGraph& cg, GGraph* fg, std::vector<partInfo>& p) { typedef Galois::WorkList::dChunkedFIFO<8> Chunk; typedef Galois::WorkList::OrderedByIntegerMetric<gainIndexer, Chunk, 10> pG; gainIndexer::g = &cg; Galois::InsertBag<GNode> boundary; if (fg) Galois::do_all_local(cg, findBoundaryAndProject(boundary, cg, *fg), Galois::loopname("boundary")); else Galois::do_all_local(cg, findBoundary(boundary, cg), Galois::loopname("boundary")); Galois::for_each_local(boundary, refine_BKL2(mins, maxs, cg, fg, p), Galois::loopname("refine"), Galois::wl<pG>()); if (false) { Galois::InsertBag<GNode> boundary; Galois::do_all_local(cg, findBoundary(boundary, cg), Galois::loopname("boundary")); Galois::for_each_local(boundary, refine_BKL2(mins, maxs, cg, fg, p), Galois::loopname("refine"), Galois::wl<pG>()); } } }; struct projectPart { GGraph* fineGraph; GGraph* coarseGraph; std::vector<partInfo>& parts; projectPart(MetisGraph* Graph, std::vector<partInfo>& p) :fineGraph(Graph->getFinerGraph()->getGraph()), coarseGraph(Graph->getGraph()), parts(p) {} void operator()(GNode n) { auto& cn = coarseGraph->getData(n); unsigned part = cn.getPart(); for (unsigned x = 0; x < cn.numChildren(); ++x) fineGraph->getData(cn.getChild(x)).setPart(part); } static void go(MetisGraph* Graph, std::vector<partInfo>& p) { Galois::do_all_local(*Graph->getGraph(), projectPart(Graph, p), Galois::loopname("project")); } }; } //anon namespace int gain(GGraph& g, GNode n) { int retval = 0; unsigned int nPart = g.getData(n).getPart(); for (auto ii = g.edge_begin(n), ee =g.edge_end(n); ii != ee; ++ii) { GNode neigh = g.getEdgeDst(ii); if (g.getData(neigh).getPart() == nPart) retval -= g.getEdgeData(ii); else retval += g.getEdgeData(ii); } return retval; } struct parallelBoundary { Galois::InsertBag<GNode> &bag; GGraph& g; parallelBoundary(Galois::InsertBag<GNode> &bag, GGraph& graph):bag(bag),g(graph) { } void operator()(GNode n,Galois::UserContext<GNode>&ctx) { if (gain(g,n) > 0) bag.push(n); } }; void refineOneByOne(GGraph& g, std::vector<partInfo>& parts) { std::vector<GNode> boundary; unsigned int meanWeight =0; for (unsigned int i =0; i<parts.size(); i++) meanWeight += parts[i].partWeight; meanWeight /= parts.size(); Galois::InsertBag<GNode> boundaryBag; parallelBoundary pB(boundaryBag, g); Galois::for_each(g.begin(), g.end(), pB, Galois::loopname("Get Boundary")); for (auto ii = boundaryBag.begin(), ie =boundaryBag.end(); ii!=ie;ii++){ GNode n = (*ii) ; unsigned nPart = g.getData(n).getPart(); int part[parts.size()]; for (unsigned int i =0; i<parts.size(); i++)part[i]=0; for (auto ii = g.edge_begin(n), ee = g.edge_end(n); ii != ee; ++ii) { GNode neigh = g.getEdgeDst(ii); part[g.getData(neigh).getPart()]+=g.getEdgeData(ii); } int t = part[nPart]; unsigned int p = nPart; for (unsigned int i =0; i<parts.size(); i++) if (i!=nPart && part[i] > t && parts[nPart].partWeight> parts[i].partWeight*(98)/(100) && parts[nPart].partWeight > meanWeight*98/100){ t = part[i]; p = i; } if(p != nPart){ g.getData(n).setPart(p); parts[p].partWeight += g.getData(n).getWeight(); parts[nPart].partWeight -= g.getData(n).getWeight(); } } } void refine_BKL(GGraph& g, std::vector<partInfo>& parts) { std::set<GNode> boundary; //find boundary nodes with positive gain Galois::InsertBag<GNode> boundaryBag; parallelBoundary pB(boundaryBag, g); Galois::for_each(g.begin(), g.end(), pB, Galois::loopname("Get Boundary")); for (auto ii = boundaryBag.begin(), ie =boundaryBag.end(); ii!=ie;ii++ ){ boundary.insert(*ii);} //refine by swapping with a neighbor high-gain node while (!boundary.empty()) { GNode n = *boundary.begin(); boundary.erase(boundary.begin()); unsigned nPart = g.getData(n).getPart(); for (auto ii = g.edge_begin(n), ee = g.edge_end(n); ii != ee; ++ii) { GNode neigh = g.getEdgeDst(ii); unsigned neighPart = g.getData(neigh).getPart(); if (neighPart != nPart && boundary.count(neigh) && gain(g, n) > 0 && gain(g, neigh) > 0 ) { unsigned nWeight = g.getData(n).getWeight(); unsigned neighWeight = g.getData(neigh).getWeight(); //swap g.getData(n).setPart(neighPart); g.getData(neigh).setPart(nPart); //update partinfo parts[neighPart].partWeight += nWeight; parts[neighPart].partWeight -= neighWeight; parts[nPart].partWeight += neighWeight; parts[nPart].partWeight -= nWeight; //remove nodes boundary.erase(neigh); break; } } } } struct ChangePart {//move each node to its nearest cluster GGraph& g; int nbCluster; double* Dist; int* card; ChangePart(GGraph& g, int nb_cluster, double* Dist, int* card): g(g), nbCluster(nb_cluster), Dist(Dist), card(card){ } void operator()(GNode n, Galois::UserContext<GNode>& ctx) { double dmin; int partition =-1; std::map <int, int> degreein; degreein[g.getData(n, Galois::MethodFlag::NONE).getOldPart()] +=1; for (GGraph::edge_iterator ii = g.edge_begin(n, Galois::MethodFlag::NONE), ei = g.edge_end(n, Galois::MethodFlag::NONE); ii != ei; ++ii){ int nclust = g.getData(g.getEdgeDst(ii), Galois::MethodFlag::NONE).getOldPart(); degreein[nclust] += (int) g.getEdgeData(ii, Galois::MethodFlag::NONE); } for(auto clust = degreein.begin(), ee = degreein.end(); clust != ee; clust++) { //the distance between the cluster clust and the noden is : double d = Dist[clust->first]-(2.0*(double)clust->second/(double)card[clust->first]); if(d < dmin || partition ==-1) { dmin = d; partition = clust->first; } } g.getData(n, Galois::MethodFlag::NONE).setPart(partition); } }; // Galois::GAccumulator<size_t> count struct ComputeClusterDist { GGraph& g; int nbCluster; Galois::GAccumulator<size_t> *card; Galois::GAccumulator<size_t> *degreeIn; ComputeClusterDist(GGraph& g, int nb_cluster): g(g), nbCluster(nb_cluster) { card = new Galois::GAccumulator<size_t>[nbCluster]; degreeIn = new Galois::GAccumulator<size_t>[nbCluster]; } /*~ComputeClusterDist(){ std::cout <<"destruct\n"; delete[] card; delete[] degreeIn; }*/ void operator()(GNode n, Galois::UserContext<GNode>& ctx) { unsigned int clust = g.getData(n, Galois::MethodFlag::NONE).getPart(); int degreet =0; g.getData(n, Galois::MethodFlag::NONE).OldPartCpyNew(); for (GGraph::edge_iterator ii = g.edge_begin(n, Galois::MethodFlag::NONE), ei = g.edge_end(n, Galois::MethodFlag::NONE); ii != ei; ++ii) if (g.getData(g.getEdgeDst(ii), Galois::MethodFlag::NONE).getPart() == clust) degreet+=(int) g.getEdgeData(ii, Galois::MethodFlag::NONE); card[clust]+=g.getData(n, Galois::MethodFlag::NONE).getWeight(); degreeIn[clust] += degreet; } }; double ratiocut(int nbClust, int* degree, int* card) { double res=0; for (int i=0; i<nbClust;i++) res += (double)(degree[i])/(double)(card[i]); return res; } void GraclusRefining(GGraph* graph, int nbParti, int nbIter) { nbIter = std::min(15, nbIter); double Dist[nbParti]; int card[nbParti]; int degreeIn[nbParti]; for(int j=0;j<nbIter;j++) { Galois::StatTimer T3("1st loop"); T3.start(); ComputeClusterDist comp(*graph, nbParti); Galois::for_each(graph->begin(), graph->end(), comp, Galois::loopname("compute dists")); T3.stop(); //std::cout << "Time calc: "<<T3.get()<<'\n'; for (int i=0; i<nbParti; i++) { card[i] = comp.card[i].reduce(); Dist[i] = (card[i]!=0)?(double)((degreeIn[i]= comp.degreeIn[i].reduce())+card[i] )/((double)card[i]*(double)card[i]) : 0; } delete[] comp.card; delete[] comp.degreeIn; Galois::StatTimer T4("2nd loop"); T4.start(); Galois::for_each(graph->begin(), graph->end(), ChangePart(*graph, nbParti, Dist, card), Galois::loopname("make moves")); T4.stop(); //std::cout << "Time move: "<<T4.get()<<'\n'; } /* std::cout<<ratiocut(nbParti, degreeIn, card)<< '\n'; for (int i=0; i<nbParti; i++) std::cout<<card[i]<< ' '; std::cout<<std::endl;*/ } void refine(MetisGraph* coarseGraph, std::vector<partInfo>& parts, unsigned minSize, unsigned maxSize, refinementMode refM, bool verbose) { MetisGraph* tGraph = coarseGraph; int nbIter=1; if (refM == GRACLUS) { while ((tGraph = tGraph->getFinerGraph())) nbIter*=2; nbIter /=4; } do { MetisGraph* fineGraph = coarseGraph->getFinerGraph(); bool doProject = true; if (verbose) { std::cout << "Cut " << computeCut(*coarseGraph->getGraph()) << " Weights "; printPartStats(parts); std::cout << "\n"; } //refine nparts times switch (refM) { case BKL2: refine_BKL2<false>::go(minSize, maxSize, *coarseGraph->getGraph(), fineGraph ? fineGraph->getGraph() : nullptr, parts); doProject = false; break; case BKL: refine_BKL(*coarseGraph->getGraph(), parts); break; case ROBO: refineOneByOne(*coarseGraph->getGraph(), parts); break; case GRACLUS: GraclusRefining(coarseGraph->getGraph(), parts.size(), nbIter);nbIter =(nbIter+1)/2;break; default: abort(); } //project up if (fineGraph && doProject) { projectPart::go(coarseGraph, parts); } } while ((coarseGraph = coarseGraph->getFinerGraph())); } /* void balance(MetisGraph* coarseGraph, std::vector<partInfo>& parts, unsigned meanSize) { MetisGraph* fineGraph = coarseGraph->getFinerGraph(); refine_BKL2<true>::go(meanSize, *coarseGraph->getGraph(), fineGraph ? fineGraph->getGraph() : nullptr, parts); } */
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/gmetis/Metis.h
/** GMetis -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author Xin Sui <[email protected]> * @author Nikunj Yadav <[email protected]> * @author Andrew Lenharth <[email protected]> */ #ifndef METIS_H_ #define METIS_H_ #include "Galois/Graph/LC_Morph_Graph.h" class MetisNode; typedef Galois::Graph::LC_Morph_Graph<MetisNode, int> GGraph; typedef Galois::Graph::LC_Morph_Graph<MetisNode, int>::GraphNode GNode; //algorithms enum InitialPartMode {GGP, GGGP, MGGGP}; enum refinementMode {BKL, BKL2, ROBO, GRACLUS}; //Nodes in the metis graph class MetisNode { struct coarsenData { int matched:1; int failedmatch:1; GNode parent; }; struct refineData { unsigned partition; unsigned oldPartition; bool maybeBoundary; }; void initCoarsen(){ data.cd.matched = false; data.cd.failedmatch = false; data.cd.parent = NULL; } public: //int num; explicit MetisNode(int weight) :_weight(weight) { initCoarsen(); } MetisNode(unsigned weight, GNode child0, GNode child1 = NULL) : _weight(weight) { initCoarsen(); children[0] = child0; children[1] = child1; } MetisNode():_weight(1) { initCoarsen(); } //call to switch data to refining void initRefine(unsigned part = 0, bool bound = false) { refineData rd = {part, part, bound}; data.rd = rd; } int getWeight() const { return _weight; } void setWeight(int weight) { _weight = weight; } void setParent(GNode p) { data.cd.parent = p; } GNode getParent() const { assert(data.cd.parent); return data.cd.parent; } void setMatched() { data.cd.matched = true; } bool isMatched() const { return data.cd.matched; } void setFailedMatch() { data.cd.failedmatch = true; } bool isFailedMatch() const { return data.cd.failedmatch; } GNode getChild(unsigned x) const { return children[x]; } unsigned numChildren() const { return children[1] ? 2 : 1; } unsigned getPart() const { return data.rd.partition; } void setPart(unsigned val) { data.rd.partition = val; } int getOldPart() const {return data.rd.oldPartition;} void OldPartCpyNew(){ data.rd.oldPartition = data.rd.partition; } bool getmaybeBoundary() const {return data.rd.maybeBoundary; } void setmaybeBoundary(bool val){ data.rd.maybeBoundary = val; } private: union { coarsenData cd; refineData rd; } data; GNode children[2]; unsigned _weight; }; //Structure to keep track of graph hirarchy class MetisGraph{ MetisGraph* coarser; MetisGraph* finer; GGraph graph; public: MetisGraph() :coarser(0), finer(0) { } explicit MetisGraph(MetisGraph* finerGraph) :coarser(0), finer(finerGraph) { finer->coarser = this; } const GGraph* getGraph() const { return &graph; } GGraph* getGraph() { return &graph; } MetisGraph* getFinerGraph() const { return finer; } MetisGraph* getCoarserGraph() const { return coarser; } unsigned getNumNodes() { return std::distance(graph.begin(), graph.end()); } unsigned getTotalWeight() { MetisGraph* f = this; while (f->finer) f = f->finer; return std::distance(f->graph.begin(), f->graph.end()); } }; //Structure to store working partition information struct partInfo { unsigned partNum; unsigned partMask; unsigned partWeight; explicit partInfo(unsigned mw) :partNum(0), partMask(1), partWeight(mw) {} partInfo() :partNum(~0), partMask(~0), partWeight(~0) {} partInfo(unsigned pn, unsigned pm, unsigned pw) :partNum(pn), partMask(pm), partWeight(pw) {} unsigned splitID() const { return partNum | partMask; } std::pair<unsigned, unsigned> splitRatio(unsigned numParts) { unsigned L = 0, R = 0; unsigned LM = partMask - 1; // 00100 -> 00011 for (unsigned x = 0; x < numParts; ++x) if ((x & LM) == partNum) { if (x & partMask) ++R; else ++L; } return std::make_pair(L, R); } partInfo split() { partInfo np(splitID(), partMask << 1, 0); partMask <<= 1; return np; } }; std::ostream& operator<<(std::ostream& os, const partInfo& p); //Metrics void printPartStats(std::vector<partInfo>&); unsigned graphStat(GGraph* graph); std::vector<unsigned> edgeCut(GGraph& g, unsigned nparts); void printCuts(const char* str, MetisGraph* g, unsigned numPartitions); unsigned computeCut(GGraph& g); //Coarsening MetisGraph* coarsen(MetisGraph* fineMetisGraph, unsigned coarsenTo, bool verbose); //Partitioning std::vector<partInfo> partition(MetisGraph* coarseMetisGraph, unsigned numPartitions, InitialPartMode partMode); std::vector<partInfo> BisectAll(MetisGraph* mcg, unsigned numPartitions, unsigned maxSize); //Refinement void refine(MetisGraph* coarseGraph, std::vector<partInfo>& parts, unsigned minSize, unsigned maxSize, refinementMode refM, bool verbose); //void refinePart(GGraph& g, std::vector<partInfo>& parts, unsigned maxSize); //Balancing void balance(MetisGraph* Graph, std::vector<partInfo>& parts, unsigned maxSize); #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/gmetis/Metric.cpp
/** GMetis -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2013, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author Xin Sui <[email protected]> * @author Andrew Lenharth <[email protected]> */ #include "Metis.h" #include <iomanip> #include <iostream> #include <numeric> struct onlineStat { unsigned num; unsigned val; double valSQ; unsigned mmin; unsigned mmax; onlineStat() :num(0), val(0), valSQ(0), mmin(std::numeric_limits<unsigned>::max()), mmax(0) {} void add(unsigned v) { ++num; val += v; valSQ += (double)v*(double)v; mmin = std::min(v, mmin); mmax = std::max(v, mmax); } double mean() { return (double)val / (double)num; } double variance() { double t = valSQ / (double)num; double m = mean(); return t - m*m; } unsigned count() { return num; } unsigned total() { return val; } unsigned min() { return mmin; } unsigned max() { return mmax; } }; unsigned graphStat(GGraph* graph) { onlineStat e; for (auto ii = graph->begin(), ee = graph->end(); ii != ee; ++ii) { unsigned val = std::distance(graph->edge_begin(*ii), graph->edge_end(*ii)); e.add(val); } std::cout << "Nodes " << e.count() << " Edges(total, var, min, max) " << e.total() << " " << e.variance() << " " << e.min() << " " << e.max(); return e.count(); } std::vector<unsigned> edgeCut(GGraph& g, unsigned nparts) { std::vector<unsigned> cuts(nparts); //find boundary nodes with positive gain for (auto nn = g.begin(), en = g.end(); nn != en; ++nn) { unsigned gPart = g.getData(*nn).getPart(); for (auto ii = g.edge_begin(*nn), ee = g.edge_end(*nn); ii != ee; ++ii) { auto& m = g.getData(g.getEdgeDst(ii)); if (m.getPart() != gPart) { cuts.at(gPart) += g.getEdgeData(ii); } } } return cuts; } unsigned computeCut(GGraph& g) { unsigned cuts=0; for (auto nn = g.begin(), en = g.end(); nn != en; ++nn) { unsigned gPart = g.getData(*nn).getPart(); for (auto ii = g.edge_begin(*nn), ee = g.edge_end(*nn); ii != ee; ++ii) { auto& m = g.getData(g.getEdgeDst(ii)); if (m.getPart() != gPart) cuts += g.getEdgeData(ii); } } return cuts/2; } void printPartStats(std::vector<partInfo>& parts) { onlineStat e; for (unsigned x = 0; x < parts.size(); ++x) { e.add(parts[x].partWeight); } std::cout << "target " << e.total() / e.count() << " var " << e.variance() << " min " << e.min() << " max " << e.max(); } std::ostream& operator<<(std::ostream& os, const partInfo& p) { os << "Num " << std::setw(3) << p.partNum << "\tmask " << std::setw(5) << std::hex << p.partMask << std::dec << "\tweight " << p.partWeight; return os; } void printCuts(const char* str, MetisGraph* g, unsigned numPartitions) { std::vector<unsigned> ec = edgeCut(*g->getGraph(), numPartitions); std::cout << str << " Edge Cuts:\n"; for (unsigned x = 0; x < ec.size(); ++x) std::cout << (x == 0 ? "" : " " ) << ec[x]; std::cout << "\n"; std::cout << str << " Average Edge Cut: " << (std::accumulate(ec.begin(), ec.end(), 0) / ec.size()) << "\n"; std::cout << str << " Minimum Edge Cut: " << *std::min_element(ec.begin(), ec.end()) << "\n"; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/gmetis/GMetis.cpp
/** GMetis -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2013, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author Xin Sui <[email protected]> * @author Andrew Lenharth <[email protected]> */ #include <vector> #include <iostream> #include <string.h> #include <stdlib.h> #include <numeric> #include <algorithm> #include <cmath> #include <fstream> #include "Metis.h" #include "Galois/Graph/Util.h" #include "Galois/Statistic.h" //#include "GraphReader.h" #include "Lonestar/BoilerPlate.h" namespace cll = llvm::cl; static const char* name = "GMetis"; static const char* desc = "Partitions a graph into K parts and minimizing the graph cut"; static const char* url = "gMetis"; static cll::opt<InitialPartMode> partMode(cll::desc("Choose a inital part mode:"), cll::values( clEnumVal(GGP, "GGP."), clEnumVal(GGGP, "GGGP, default."), clEnumVal(MGGGP, "MGGGP."), clEnumValEnd), cll::init(GGGP)); static cll::opt<refinementMode> refineMode(cll::desc("Choose a refinement mode:"), cll::values( clEnumVal(BKL, "BKL"), clEnumVal(BKL2, "BKL2, default."), clEnumVal(ROBO, "ROBO"), clEnumVal(GRACLUS, "GRACLUS"), clEnumValEnd), cll::init(BKL2)); static cll::opt<bool> mtxInput("mtxinput", cll::desc("Use text mtx files instead binary based ones"), cll::init(false)); static cll::opt<bool> weighted("weighted", cll::desc("weighted"), cll::init(false)); static cll::opt<bool> verbose("verbose", cll::desc("verbose output (debugging mode, takes extra time)"), cll::init(false)); static cll::opt<std::string> outfile("output", cll::desc("output file name")); static cll::opt<std::string> filename(cll::Positional, cll::desc("<input file>"), cll::Required); static cll::opt<int> numPartitions(cll::Positional, cll::desc("<Number of partitions>"), cll::Required); static cll::opt<double> imbalance("balance", cll::desc("Fraction deviated from mean partition size"), cll::init(0.01)); const double COARSEN_FRACTION = 0.9; /** * KMetis Algorithm */ void Partition(MetisGraph* metisGraph, unsigned nparts) { Galois::StatTimer TM; TM.start(); unsigned meanWeight = ( (double)metisGraph->getTotalWeight()) / (double)nparts; //unsigned coarsenTo = std::max(metisGraph->getNumNodes() / (40 * intlog2(nparts)), 20 * (nparts)); unsigned coarsenTo = 20 * nparts; if (verbose) std::cout << "Starting coarsening: \n"; Galois::StatTimer T("Coarsen"); T.start(); MetisGraph* mcg = coarsen(metisGraph, coarsenTo, verbose); T.stop(); if (verbose) std::cout << "Time coarsen: " << T.get() << "\n"; Galois::StatTimer T2("Partition"); T2.start(); std::vector<partInfo> parts; parts = partition(mcg, nparts, partMode); T2.stop(); if (verbose) std::cout << "Init edge cut : " << computeCut(*mcg->getGraph()) << "\n\n"; std::vector<partInfo> initParts = parts; std::cout << "Time clustering: "<<T2.get()<<'\n'; if (verbose) switch (refineMode) { case BKL2: std::cout<< "Sarting refinnement with BKL2\n"; break; case BKL: std::cout<< "Sarting refinnement with BKL\n"; break; case ROBO: std::cout<< "Sarting refinnement with ROBO\n"; break; case GRACLUS: std::cout<< "Sarting refinnement with GRACLUS\n"; break; default: abort(); } Galois::StatTimer T3("Refine"); T3.start(); refine(mcg, parts, meanWeight - (unsigned)(meanWeight * imbalance), meanWeight + (unsigned)(meanWeight * imbalance), refineMode, verbose); T3.stop(); if (verbose) std::cout << "Time refinement: " << T3.get() << "\n"; TM.stop(); std::cout << "Initial dist\n"; printPartStats(initParts); std::cout << "Refined dist\n"; printPartStats(parts); std::cout << "\nTime: " << TM.get() << '\n'; return; } //printGraphBeg(*graph) struct parallelInitMorphGraph { GGraph &graph; parallelInitMorphGraph(GGraph &g):graph(g) { } void operator()(GNode node) { for(GGraph::edge_iterator jj = graph.edge_begin(node),kk=graph.edge_end(node);jj!=kk;jj++) { graph.getEdgeData(jj)=1; // weight+=1; } } }; int main(int argc, char** argv) { Galois::StatManager statManager; LonestarStart(argc, argv, name, desc, url); srand(-1); MetisGraph metisGraph; GGraph* graph = metisGraph.getGraph(); Galois::Graph::readGraph(*graph, filename); Galois::do_all_local(*graph, parallelInitMorphGraph(*graph)); graphStat(graph); std::cout << "\n"; //printGraphBeg(*graph); Galois::reportPageAlloc("MeminfoPre"); Galois::preAlloc(Galois::Runtime::MM::numPageAllocTotal() * 5); Partition(&metisGraph, numPartitions); Galois::reportPageAlloc("MeminfoPost"); std::cout << "Total edge cut: " << computeCut(*graph) << "\n"; if (outfile != "") { MetisGraph* coarseGraph = &metisGraph; while (coarseGraph->getCoarserGraph()) coarseGraph = coarseGraph->getCoarserGraph(); std::ofstream outFile(outfile.c_str()); for (auto it = graph->begin(), ie = graph->end(); it!=ie; it++) { unsigned gPart = graph->getData(*it).getPart(); outFile<< gPart<< '\n'; } } return 0; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/preflowpush/CMakeLists.txt
app(preflowpush Preflowpush.cpp)
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/preflowpush/Preflowpush.cpp
/** Preflow-push application -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2013, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author Donald Nguyen <[email protected]> */ #include "Galois/Galois.h" #include "Galois/Accumulator.h" #include "Galois/Statistic.h" #include "Galois/Bag.h" #include "Galois/Graph/LCGraph.h" #include "llvm/Support/CommandLine.h" #ifdef GALOIS_USE_EXP #include "Galois/PriorityScheduling.h" #endif #include "Lonestar/BoilerPlate.h" #include <iostream> #include <fstream> namespace cll = llvm::cl; const char* name = "Preflow Push"; const char* desc = "Finds the maximum flow in a network using the preflow push technique"; const char* url = "preflow_push"; enum DetAlgo { nondet, detBase, detDisjoint }; static cll::opt<std::string> filename(cll::Positional, cll::desc("<input file>"), cll::Required); static cll::opt<uint32_t> sourceId(cll::Positional, cll::desc("sourceID"), cll::Required); static cll::opt<uint32_t> sinkId(cll::Positional, cll::desc("sinkID"), cll::Required); static cll::opt<bool> useHLOrder("useHLOrder", cll::desc("Use HL ordering heuristic"), cll::init(false)); static cll::opt<bool> useUnitCapacity("useUnitCapacity", cll::desc("Assume all capacities are unit"), cll::init(false)); static cll::opt<bool> useSymmetricDirectly("useSymmetricDirectly", cll::desc("Assume input graph is symmetric and has unit capacities"), cll::init(false)); static cll::opt<int> relabelInt("relabel", cll::desc("relabel interval: < 0 no relabeling, 0 use default interval, > 0 relabel every X iterations"), cll::init(0)); static cll::opt<DetAlgo> detAlgo(cll::desc("Deterministic algorithm:"), cll::values( clEnumVal(nondet, "Non-deterministic"), clEnumVal(detBase, "Base execution"), clEnumVal(detDisjoint, "Disjoint execution"), clEnumValEnd), cll::init(nondet)); /** * Alpha parameter the original Goldberg algorithm to control when global * relabeling occurs. For comparison purposes, we keep them the same as * before, but it is possible to achieve much better performance by adjusting * the global relabel frequency. */ const int ALPHA = 6; /** * Beta parameter the original Goldberg algorithm to control when global * relabeling occurs. For comparison purposes, we keep them the same as * before, but it is possible to achieve much better performance by adjusting * the global relabel frequency. */ const int BETA = 12; struct Node { uint32_t id; size_t excess; int height; int current; Node() : excess(0), height(1), current(0) { } }; std::ostream& operator<<(std::ostream& os, const Node& n) { os << "(" << "id: " << n.id << ", excess: " << n.excess << ", height: " << n.height << ", current: " << n.current << ")"; return os; } typedef Galois::Graph::LC_Linear_Graph<Node, int32_t>::with_numa_alloc<true>::type Graph; typedef Graph::GraphNode GNode; struct Config { Graph graph; GNode sink; GNode source; int global_relabel_interval; bool should_global_relabel; Config() : should_global_relabel(false) {} }; Config app; struct Indexer :std::unary_function<GNode, int> { int operator()(const GNode& n) const { return -app.graph.getData(n, Galois::MethodFlag::NONE).height; } }; struct GLess :std::binary_function<GNode, GNode, bool> { bool operator()(const GNode& lhs, const GNode& rhs) const { int lv = -app.graph.getData(lhs, Galois::MethodFlag::NONE).height; int rv = -app.graph.getData(rhs, Galois::MethodFlag::NONE).height; return lv < rv; } }; struct GGreater :std::binary_function<GNode, GNode, bool> { bool operator()(const GNode& lhs, const GNode& rhs) const { int lv = -app.graph.getData(lhs, Galois::MethodFlag::NONE).height; int rv = -app.graph.getData(rhs, Galois::MethodFlag::NONE).height; return lv > rv; } }; void checkAugmentingPath() { // Use id field as visited flag for (Graph::iterator ii = app.graph.begin(), ee = app.graph.end(); ii != ee; ++ii) { GNode src = *ii; app.graph.getData(src).id = 0; } std::deque<GNode> queue; app.graph.getData(app.source).id = 1; queue.push_back(app.source); while (!queue.empty()) { GNode& src = queue.front(); queue.pop_front(); for (Graph::edge_iterator ii = app.graph.edge_begin(src), ee = app.graph.edge_end(src); ii != ee; ++ii) { GNode dst = app.graph.getEdgeDst(ii); if (app.graph.getData(dst).id == 0 && app.graph.getEdgeData(ii) > 0) { app.graph.getData(dst).id = 1; queue.push_back(dst); } } } if (app.graph.getData(app.sink).id != 0) { assert(false && "Augmenting path exisits"); abort(); } } void checkHeights() { for (Graph::iterator ii = app.graph.begin(), ei = app.graph.end(); ii != ei; ++ii) { GNode src = *ii; int sh = app.graph.getData(src).height; for (Graph::edge_iterator jj = app.graph.edge_begin(src), ej = app.graph.edge_end(src); jj != ej; ++jj) { GNode dst = app.graph.getEdgeDst(jj); int cap = app.graph.getEdgeData(jj); int dh = app.graph.getData(dst).height; if (cap > 0 && sh > dh + 1) { std::cerr << "height violated at " << app.graph.getData(src) << "\n"; abort(); } } } } Graph::edge_iterator findEdge(Graph& g, GNode src, GNode dst) { Graph::edge_iterator ii = g.edge_begin(src, Galois::MethodFlag::NONE), ei = g.edge_end(src, Galois::MethodFlag::NONE); for (; ii != ei; ++ii) { if (g.getEdgeDst(ii) == dst) break; } return ii; } void checkConservation(Config& orig) { std::vector<GNode> map; map.resize(app.graph.size()); // Setup ids assuming same iteration order in both graphs uint32_t id = 0; for (Graph::iterator ii = app.graph.begin(), ei = app.graph.end(); ii != ei; ++ii, ++id) { app.graph.getData(*ii).id = id; } id = 0; for (Graph::iterator ii = orig.graph.begin(), ei = orig.graph.end(); ii != ei; ++ii, ++id) { orig.graph.getData(*ii).id = id; map[id] = *ii; } // Now do some checking for (Graph::iterator ii = app.graph.begin(), ei = app.graph.end(); ii != ei; ++ii) { GNode src = *ii; const Node& node = app.graph.getData(src); uint32_t srcId = node.id; if (src == app.source || src == app.sink) continue; if (node.excess != 0 && node.height != (int) app.graph.size()) { std::cerr << "Non-zero excess at " << node << "\n"; abort(); } size_t sum = 0; for (Graph::edge_iterator jj = app.graph.edge_begin(src), ej = app.graph.edge_end(src); jj != ej; ++jj) { GNode dst = app.graph.getEdgeDst(jj); uint32_t dstId = app.graph.getData(dst).id; int ocap = orig.graph.getEdgeData(findEdge(orig.graph, map[srcId], map[dstId])); int delta = 0; if (ocap > 0) delta -= ocap - app.graph.getEdgeData(jj); else delta += app.graph.getEdgeData(jj); sum += delta; } if (node.excess != sum) { std::cerr << "Not pseudoflow: " << node.excess << " != " << sum << " at " << node << "\n"; abort(); } } } void verify(Config& orig) { // FIXME: doesn't fully check result checkHeights(); checkConservation(orig); checkAugmentingPath(); } void reduceCapacity(const Graph::edge_iterator& ii, const GNode& src, const GNode& dst, int amount) { Graph::edge_data_type& cap1 = app.graph.getEdgeData(ii); Graph::edge_data_type& cap2 = app.graph.getEdgeData(findEdge(app.graph, dst, src)); cap1 -= amount; cap2 += amount; } template<DetAlgo version,bool useCAS=true> struct UpdateHeights { //typedef int tt_does_not_need_aborts; typedef int tt_needs_per_iter_alloc; // For LocalState struct LocalState { LocalState(UpdateHeights<version,useCAS>& self, Galois::PerIterAllocTy& alloc) { } }; typedef LocalState GaloisDeterministicLocalState; static_assert(Galois::has_deterministic_local_state<UpdateHeights>::value, "Oops"); //struct IdFn { // unsigned long operator()(const GNode& item) const { // return app.graph.getData(item, Galois::MethodFlag::NONE).id; // } //}; /** * Do reverse BFS on residual graph. */ void operator()(const GNode& src, Galois::UserContext<GNode>& ctx) { if (version != nondet) { bool used = false; if (version == detDisjoint) { ctx.getLocalState(used); } if (!used) { for (Graph::edge_iterator ii = app.graph.edge_begin(src, Galois::MethodFlag::CHECK_CONFLICT), ee = app.graph.edge_end(src, Galois::MethodFlag::CHECK_CONFLICT); ii != ee; ++ii) { GNode dst = app.graph.getEdgeDst(ii); int rdata = app.graph.getEdgeData(findEdge(app.graph, dst, src)); if (rdata > 0) { app.graph.getData(dst, Galois::MethodFlag::CHECK_CONFLICT); } } } if (version == detDisjoint) { if (!used) return; } else { app.graph.getData(src, Galois::MethodFlag::WRITE); } } for (Graph::edge_iterator ii = app.graph.edge_begin(src, useCAS ? Galois::MethodFlag::NONE : Galois::MethodFlag::CHECK_CONFLICT), ee = app.graph.edge_end(src, useCAS ? Galois::MethodFlag::NONE : Galois::MethodFlag::CHECK_CONFLICT); ii != ee; ++ii) { GNode dst = app.graph.getEdgeDst(ii); int rdata = app.graph.getEdgeData(findEdge(app.graph, dst, src)); if (rdata > 0) { Node& node = app.graph.getData(dst, Galois::MethodFlag::NONE); int newHeight = app.graph.getData(src, Galois::MethodFlag::NONE).height + 1; if (useCAS) { int oldHeight; while (newHeight < (oldHeight = node.height)) { if (__sync_bool_compare_and_swap(&node.height, oldHeight, newHeight)) { ctx.push(dst); break; } } } else { if (newHeight < node.height) { node.height = newHeight; ctx.push(dst); } } } } } }; struct ResetHeights { void operator()(const GNode& src) { Node& node = app.graph.getData(src, Galois::MethodFlag::NONE); node.height = app.graph.size(); node.current = 0; if (src == app.sink) node.height = 0; } }; template<typename WLTy> struct FindWork { WLTy& wl; FindWork(WLTy& w) : wl(w) {} void operator()(const GNode& src) { Node& node = app.graph.getData(src, Galois::MethodFlag::NONE); if (src == app.sink || src == app.source || node.height >= (int) app.graph.size()) return; if (node.excess > 0) wl.push_back(src); } }; template<typename IncomingWL> void globalRelabel(IncomingWL& incoming) { Galois::StatTimer T1("ResetHeightsTime"); T1.start(); Galois::do_all_local(app.graph, ResetHeights(), Galois::loopname("ResetHeights")); T1.stop(); Galois::StatTimer T("UpdateHeightsTime"); T.start(); switch (detAlgo) { case nondet: #ifdef GALOIS_USE_EXP Galois::for_each(app.sink, UpdateHeights<nondet>(), Galois::loopname("UpdateHeights"), Galois::wl<Galois::WorkList::BulkSynchronousInline<>>()); #else Galois::for_each(app.sink, UpdateHeights<nondet>(), Galois::loopname("UpdateHeights")); #endif break; case detBase: Galois::for_each_det(app.sink, UpdateHeights<detBase>(), "UpdateHeights"); break; case detDisjoint: Galois::for_each_det(app.sink, UpdateHeights<detDisjoint>(), "UpdateHeights"); break; default: std::cerr << "Unknown algorithm" << detAlgo << "\n"; abort(); } T.stop(); Galois::StatTimer T2("FindWorkTime"); T2.start(); Galois::do_all_local(app.graph, FindWork<IncomingWL>(incoming), Galois::loopname("FindWork")); T2.stop(); } void acquire(const GNode& src) { // LC Graphs have a different idea of locking for (Graph::edge_iterator ii = app.graph.edge_begin(src, Galois::MethodFlag::CHECK_CONFLICT), ee = app.graph.edge_end(src, Galois::MethodFlag::CHECK_CONFLICT); ii != ee; ++ii) { GNode dst = app.graph.getEdgeDst(ii); app.graph.getData(dst, Galois::MethodFlag::CHECK_CONFLICT); } } void relabel(const GNode& src) { int minHeight = std::numeric_limits<int>::max(); int minEdge; int current = 0; for (Graph::edge_iterator ii = app.graph.edge_begin(src, Galois::MethodFlag::NONE), ee = app.graph.edge_end(src, Galois::MethodFlag::NONE); ii != ee; ++ii, ++current) { GNode dst = app.graph.getEdgeDst(ii); int cap = app.graph.getEdgeData(ii); if (cap > 0) { const Node& dnode = app.graph.getData(dst, Galois::MethodFlag::NONE); if (dnode.height < minHeight) { minHeight = dnode.height; minEdge = current; } } } assert(minHeight != std::numeric_limits<int>::max()); ++minHeight; Node& node = app.graph.getData(src, Galois::MethodFlag::NONE); if (minHeight < (int) app.graph.size()) { node.height = minHeight; node.current = minEdge; } else { node.height = app.graph.size(); } } bool discharge(const GNode& src, Galois::UserContext<GNode>& ctx) { //Node& node = app.graph.getData(src, Galois::MethodFlag::CHECK_CONFLICT); Node& node = app.graph.getData(src, Galois::MethodFlag::NONE); //int prevHeight = node.height; bool relabeled = false; if (node.excess == 0 || node.height >= (int) app.graph.size()) { return false; } while (true) { //Galois::MethodFlag flag = relabeled ? Galois::MethodFlag::NONE : Galois::MethodFlag::CHECK_CONFLICT; Galois::MethodFlag flag = Galois::MethodFlag::NONE; bool finished = false; int current = node.current; Graph::edge_iterator ii = app.graph.edge_begin(src, flag), ee = app.graph.edge_end(src, flag); std::advance(ii, node.current); for (; ii != ee; ++ii, ++current) { GNode dst = app.graph.getEdgeDst(ii); int cap = app.graph.getEdgeData(ii); if (cap == 0)// || current < node.current) continue; Node& dnode = app.graph.getData(dst, Galois::MethodFlag::NONE); if (node.height - 1 != dnode.height) continue; // Push flow int amount = std::min(static_cast<int>(node.excess), cap); reduceCapacity(ii, src, dst, amount); // Only add once if (dst != app.sink && dst != app.source && dnode.excess == 0) ctx.push(dst); node.excess -= amount; dnode.excess += amount; if (node.excess == 0) { finished = true; node.current = current; break; } } if (finished) break; relabel(src); relabeled = true; if (node.height == (int) app.graph.size()) break; //prevHeight = node.height; } return relabeled; } struct Counter { Galois::GAccumulator<int> accum; Galois::Runtime::PerThreadStorage<int> local; }; template<DetAlgo version> struct Process { typedef int tt_needs_parallel_break; typedef int tt_needs_per_iter_alloc; // For LocalState struct LocalState { LocalState(Process<version>& self, Galois::PerIterAllocTy& alloc) { } }; typedef LocalState GaloisDeterministicLocalState; static_assert(Galois::has_deterministic_local_state<Process>::value, "Oops"); uintptr_t galoisDeterministicId(const GNode& item) const { return app.graph.getData(item, Galois::MethodFlag::NONE).id; } static_assert(Galois::has_deterministic_id<Process>::value, "Oops"); bool galoisDeterministicParallelBreak() { if (app.global_relabel_interval > 0 && counter.accum.reduce() >= app.global_relabel_interval) { app.should_global_relabel = true; return true; } return false; } static_assert(Galois::has_deterministic_parallel_break<Process>::value, "Oops"); Counter& counter; Process(Counter& c): counter(c) { } void operator()(GNode& src, Galois::UserContext<GNode>& ctx) { if (version != nondet) { bool used = false; if (version == detDisjoint) { ctx.getLocalState(used); } if (!used) { acquire(src); } if (version == detDisjoint) { if (!used) return; } else { app.graph.getData(src, Galois::MethodFlag::WRITE); } } int increment = 1; if (discharge(src, ctx)) { increment += BETA; } counter.accum += increment; } }; template<> struct Process<nondet> { typedef int tt_needs_parallel_break; Counter& counter; int limit; Process(Counter& c): counter(c) { limit = app.global_relabel_interval / numThreads; } void operator()(GNode& src, Galois::UserContext<GNode>& ctx) { int increment = 1; acquire(src); if (discharge(src, ctx)) { increment += BETA; } int v = *counter.local.getLocal() += increment; if (app.global_relabel_interval > 0 && v >= limit) { app.should_global_relabel = true; ctx.breakLoop(); return; } } }; template<typename EdgeTy> void writePfpGraph(const std::string& inputFile, const std::string& outputFile) { typedef Galois::Graph::FileGraph ReaderGraph; typedef ReaderGraph::GraphNode ReaderGNode; ReaderGraph reader; reader.structureFromFile(inputFile); typedef Galois::Graph::FileGraphWriter Writer; typedef Galois::LargeArray<EdgeTy> EdgeData; typedef typename EdgeData::value_type edge_value_type; Writer p; EdgeData edgeData; // Count edges size_t numEdges = 0; for (ReaderGraph::iterator ii = reader.begin(), ei = reader.end(); ii != ei; ++ii) { ReaderGNode rsrc = *ii; for (ReaderGraph::edge_iterator jj = reader.edge_begin(rsrc), ej = reader.edge_end(rsrc); jj != ej; ++jj) { ReaderGNode rdst = reader.getEdgeDst(jj); if (rsrc == rdst) continue; if (!reader.hasNeighbor(rdst, rsrc)) ++numEdges; ++numEdges; } } p.setNumNodes(reader.size()); p.setNumEdges(numEdges); p.setSizeofEdgeData(sizeof(edge_value_type)); p.phase1(); for (ReaderGraph::iterator ii = reader.begin(), ei = reader.end(); ii != ei; ++ii) { ReaderGNode rsrc = *ii; for (ReaderGraph::edge_iterator jj = reader.edge_begin(rsrc), ej = reader.edge_end(rsrc); jj != ej; ++jj) { ReaderGNode rdst = reader.getEdgeDst(jj); if (rsrc == rdst) continue; if (!reader.hasNeighbor(rdst, rsrc)) p.incrementDegree(rdst); p.incrementDegree(rsrc); } } EdgeTy one = 1; static_assert(sizeof(one) == sizeof(uint32_t), "Unexpected edge data size"); one = Galois::convert_le32(one); p.phase2(); edgeData.create(numEdges); for (ReaderGraph::iterator ii = reader.begin(), ei = reader.end(); ii != ei; ++ii) { ReaderGNode rsrc = *ii; for (ReaderGraph::edge_iterator jj = reader.edge_begin(rsrc), ej = reader.edge_end(rsrc); jj != ej; ++jj) { ReaderGNode rdst = reader.getEdgeDst(jj); if (rsrc == rdst) continue; if (!reader.hasNeighbor(rdst, rsrc)) edgeData.set(p.addNeighbor(rdst, rsrc), 0); EdgeTy cap = useUnitCapacity ? one : reader.getEdgeData<EdgeTy>(jj); edgeData.set(p.addNeighbor(rsrc, rdst), cap); } } edge_value_type* rawEdgeData = p.finish<edge_value_type>(); std::copy(edgeData.begin(), edgeData.end(), rawEdgeData); p.structureToFile(outputFile); } void initializeGraph(std::string inputFile, uint32_t sourceId, uint32_t sinkId, Config *newApp) { if (useSymmetricDirectly) { Galois::Graph::readGraph(newApp->graph, inputFile); for (Graph::iterator ss = newApp->graph.begin(), es = newApp->graph.end(); ss != es; ++ss) { for (Graph::edge_iterator ii = newApp->graph.edge_begin(*ss), ei = newApp->graph.edge_end(*ss); ii != ei; ++ii) newApp->graph.getEdgeData(ii) = 1; } } else { if (inputFile.find(".gr.pfp") != inputFile.size() - strlen(".gr.pfp")) { std::string pfpName = inputFile + ".pfp"; std::ifstream pfpFile(pfpName.c_str()); if (!pfpFile.good()) { writePfpGraph<Graph::edge_data_type>(inputFile, pfpName); } inputFile = pfpName; } Galois::Graph::readGraph(newApp->graph, inputFile); #ifdef HAVE_BIG_ENDIAN // Convert edge data to host ordering for (Graph::iterator ss = newApp->graph.begin(), es = newApp->graph.end(); ss != es; ++ss) { for (Graph::edge_iterator ii = newApp->graph.edge_begin(*ss), ei = newApp->graph.edge_end(*ss); ii != ei; ++ii) { Graph::edge_data_type& cap = newApp->graph.getEdgeData(ii); static_assert(sizeof(cap) == sizeof(uint32_t), "Unexpected edge data size"); cap = Galois::convert_le32(cap); } } #endif } Graph& g = newApp->graph; if (sourceId == sinkId || sourceId >= g.size() || sinkId >= g.size()) { std::cerr << "invalid source or sink id\n"; abort(); } uint32_t id = 0; for (Graph::iterator ii = g.begin(), ei = g.end(); ii != ei; ++ii, ++id) { if (id == sourceId) { newApp->source = *ii; g.getData(newApp->source).height = g.size(); } else if (id == sinkId) { newApp->sink = *ii; } g.getData(*ii).id = id; } } template<typename C> void initializePreflow(C& initial) { for (Graph::edge_iterator ii = app.graph.edge_begin(app.source), ee = app.graph.edge_end(app.source); ii != ee; ++ii) { GNode dst = app.graph.getEdgeDst(ii); int cap = app.graph.getEdgeData(ii); reduceCapacity(ii, app.source, dst, cap); Node& node = app.graph.getData(dst); node.excess += cap; if (cap > 0) initial.push_back(dst); } } void run() { typedef Galois::WorkList::dChunkedFIFO<16> Chunk; typedef Galois::WorkList::OrderedByIntegerMetric<Indexer,Chunk> OBIM; Galois::InsertBag<GNode> initial; initializePreflow(initial); while (initial.begin() != initial.end()) { Galois::StatTimer T_discharge("DischargeTime"); T_discharge.start(); Counter counter; switch (detAlgo) { case nondet: if (useHLOrder) { Galois::for_each_local(initial, Process<nondet>(counter), Galois::loopname("Discharge"), Galois::wl<OBIM>()); } else { Galois::for_each_local(initial, Process<nondet>(counter), Galois::loopname("Discharge")); } break; case detBase: Galois::for_each_det(initial.begin(), initial.end(), Process<detBase>(counter), "Discharge"); break; case detDisjoint: Galois::for_each_det(initial.begin(), initial.end(), Process<detDisjoint>(counter), "Discharge"); break; default: std::cerr << "Unknown algorithm" << detAlgo << "\n"; abort(); } T_discharge.stop(); if (app.should_global_relabel) { Galois::StatTimer T_global_relabel("GlobalRelabelTime"); T_global_relabel.start(); initial.clear(); globalRelabel(initial); app.should_global_relabel = false; T_global_relabel.stop(); } else { break; } } } int main(int argc, char** argv) { Galois::StatManager M; bool serial = false; LonestarStart(argc, argv, name, desc, url); initializeGraph(filename, sourceId, sinkId, &app); if (relabelInt == 0) { app.global_relabel_interval = app.graph.size() * ALPHA + app.graph.sizeEdges() / 3; } else { app.global_relabel_interval = relabelInt; } Galois::StatTimer T; T.start(); run(); T.stop(); std::cout << "max flow = " << app.graph.getData(app.sink).excess << "\n"; std::cout << "time: " << ((double)T.get()/1000) << " s\n"; if (!skipVerify) { Config orig; initializeGraph(filename, sourceId, sinkId, &orig); verify(orig); } return 0; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/delaunayrefinement/Element.h
/** Delaunay refinement -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2012, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @section Description * * @author Milind Kulkarni <[email protected]>> */ #ifndef _ELEMENT_H #define _ELEMENT_H #include "Galois/Runtime/ll/gio.h" #include <cassert> #include <stdlib.h> #include "Edge.h" #define MINANGLE 30.0 class Element { Tuple coords[3]; // The three endpoints of the triangle // if the triangle has an obtuse angle // obtuse - 1 is which one signed char obtuse; bool bDim; // true == 3, false == 2 int id; public: //! Constructor for Triangles Element(const Tuple& a, const Tuple& b, const Tuple& c, int _id = 0) :obtuse(0), bDim(true), id(_id) { coords[0] = a; coords[1] = b; coords[2] = c; if (b < a || c < a) { if (b < c) { coords[0] = b; coords[1] = c; coords[2] = a; } else { coords[0] = c; coords[1] = a; coords[2] = b; } } // edges[0] = Edge(coords[0], coords[1]); // edges[1] = Edge(coords[1], coords[2]); // edges[2] = Edge(coords[2], coords[0]); for (int i = 0; i < 3; i++) if (angleOBCheck(i)) obtuse = i + 1; //computeCenter(); } //! Constructor for segments Element(const Tuple& a, const Tuple& b, int _id = 0): obtuse(0), bDim(false), id(_id) { coords[0] = a; coords[1] = b; if (b < a) { coords[0] = b; coords[1] = a; } //computeCenter(); } Tuple getCenter() const { if (dim() == 2) { return (coords[0] + coords[1]) * 0.5; } else { const Tuple& a = coords[0]; const Tuple& b = coords[1]; const Tuple& c = coords[2]; Tuple x = b - a; Tuple y = c - a; double xlen = a.distance(b); double ylen = a.distance(c); double cosine = (x * y) / (xlen * ylen); double sine_sq = 1.0 - cosine * cosine; double plen = ylen / xlen; double s = plen * cosine; double t = plen * sine_sq; double wp = (plen - cosine) / (2 * t); double wb = 0.5 - (wp * s); Tuple tmpval = a * (1 - wb - wp); tmpval = tmpval + (b * wb); return tmpval + (c * wp); } } double get_radius_squared() const { return get_radius_squared(getCenter()); } double get_radius_squared(const Tuple& center) const { return center.distance_squared(coords[0]); } bool operator<(const Element& rhs) const { //apparently a triangle is less than a line if (dim() < rhs.dim()) return false; if (dim() > rhs.dim()) return true; for (int i = 0; i < dim(); i++) { if (coords[i] < rhs.coords[i]) return true; else if (coords[i] > rhs.coords[i]) return false; } return false; } /// @return if the current triangle has a common edge with e bool isRelated(const Element& rhs) const { int num_eq = 0; for(int i = 0; i < dim(); ++i) for(int j = 0; j < rhs.dim(); ++j) if (coords[i] == rhs.coords[j]) ++num_eq; return num_eq == 2; } bool inCircle(Tuple p) const { Tuple center = getCenter(); double ds = center.distance_squared(p); return ds <= get_radius_squared(center); } void angleCheck(int i, bool& ob, bool& sm, double M) const { int j = (i + 1) % dim(); int k = (i + 2) % dim(); Tuple::angleCheck(coords[j], coords[i], coords[k], ob, sm, M); } bool angleGTCheck(int i, double M) const { int j = (i + 1) % dim(); int k = (i + 2) % dim(); return Tuple::angleGTCheck(coords[j], coords[i], coords[k], M); } bool angleOBCheck(int i) const { int j = (i + 1) % dim(); int k = (i + 2) % dim(); return Tuple::angleOBCheck(coords[j], coords[i], coords[k]); } //Virtualize the Edges array //Used only by Mesh now Edge getEdge(int i) const { if (i == 0) return Edge(coords[0], coords[1]); if (!bDim) { if (i == 1) return Edge(coords[1], coords[0]); } else { if (i == 1) return Edge(coords[1], coords[2]); else if (i == 2) return Edge(coords[2], coords[0]); } GALOIS_DIE("unknown edge"); return Edge(coords[0], coords[0]); } Edge getOppositeObtuse() const { //The edge opposite the obtuse angle is the edge formed by //the other indexes switch (obtuse) { case 1: return getEdge(1); case 2: return getEdge(2); case 3: return getEdge(0); } GALOIS_DIE("no obtuse edge"); return getEdge(0); } //! Should the node be processed? bool isBad() const { if (!bDim) return false; for (int i = 0; i < 3; i++) if (angleGTCheck(i, MINANGLE)) return true; return false; } const Tuple& getPoint(int i) const { return coords[i]; } const Tuple& getObtuse() const { return coords[obtuse-1]; } int dim() const { return bDim ? 3 : 2; } int numEdges() const { return dim() + dim() - 3; } bool isObtuse() const { return obtuse != 0; } int getId() const { return id; } /** * Scans all the edges of the two elements and if it finds one that is * equal, then sets this as the Edge of the EdgeRelation */ Edge getRelatedEdge(const Element& e) const { int at = 0; Tuple d[2]; for(int i = 0; i < dim(); ++i) for(int j = 0; j < e.dim(); ++j) if (coords[i] == e.coords[j]) d[at++] = coords[i]; assert(at == 2); return Edge(d[0], d[1]); } std::ostream& print(std::ostream& s) const { s << '['; for (int i = 0; i < dim(); ++i) s << coords[i] << (i < (dim() - 1) ? ", " : ""); s << ']'; return s; } }; static std::ostream& operator<<(std::ostream& s, const Element& E) { return E.print(s); } #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/delaunayrefinement/Tuple.h
/** A tuple -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author Milind Kulkarni <[email protected]>> * @author Andrew Lenharth <[email protected]> */ #ifndef TUPLE_H #define TUPLE_H #include <ostream> #include <cmath> class Tuple { double _t[2]; public: Tuple(double a, double b) { _t[0] = a; _t[1] = b; } Tuple() {}; ~Tuple() {}; bool operator==(const Tuple& rhs) const { for (int x = 0; x < 2; ++x) { if (_t[x] != rhs._t[x]) return false; } return true; } bool operator!=(const Tuple& rhs) const { return !(*this == rhs); } bool operator<(const Tuple& rhs) const { for (int i = 0; i < 2; ++i) { if (_t[i] < rhs._t[i]) return true; else if (_t[i] > rhs._t[i]) return false; } return false; } bool operator>(const Tuple& rhs) const { for (int i = 0; i < 2; ++i) { if (_t[i] > rhs._t[i]) return true; else if (_t[i] < rhs._t[i]) return false; } return false; } Tuple operator+(const Tuple& rhs) const { return Tuple(_t[0]+rhs._t[0], _t[1]+rhs._t[1]); } Tuple operator-(const Tuple& rhs) const { return Tuple(_t[0]-rhs._t[0], _t[1]-rhs._t[1]); } Tuple operator*(double d) const { //scalar product return Tuple(_t[0]*d, _t[1]*d); } double operator*(const Tuple& rhs) const { //dot product return _t[0]*rhs._t[0] + _t[1]*rhs._t[1]; } double operator[](int i) const { return _t[i]; }; int cmp(const Tuple& x) const { if (*this == x) return 0; if (*this > x) return 1; return -1; } double distance_squared(const Tuple& p) const { //squared distance between current tuple and x double sum = 0.0; for (int i = 0; i < 2; ++i) { double d = _t[i] - p._t[i]; sum += d * d; } return sum; } double distance(const Tuple& p) const { //distance between current tuple and x return sqrt(distance_squared(p)); } double angle(const Tuple& a, const Tuple& b) const { //angle formed by a, current tuple, b Tuple vb = a - *this; Tuple vc = b - *this; double dp = vb*vc; double c = dp / sqrt(distance_squared(a) * distance_squared(b)); return (180/M_PI) * acos(c); } void angleCheck(const Tuple& a, const Tuple& b, bool& ob, bool& sm, double M) const { //angle formed by a, current tuple, b Tuple vb = a - *this; Tuple vc = b - *this; double dp = vb*vc; if (dp < 0) { ob = true; return; } double c = dp / sqrt(distance_squared(b) * distance_squared(a)); if (c > cos(M*M_PI/180)) { sm = true; return; } return; } bool angleGTCheck(const Tuple& a, const Tuple& b, double M) const { //angle formed by a, current tuple, b Tuple vb = a - *this; Tuple vc = b - *this; double dp = vb*vc; if (dp < 0) return false; double c = dp / sqrt(distance_squared(b) * distance_squared(a)); return c > cos(M*M_PI/180); } bool angleOBCheck(const Tuple& a, const Tuple& b) const { //angle formed by a, current tuple, b Tuple vb = a - *this; Tuple vc = b - *this; double dp = vb*vc; return dp < 0; } void print(std::ostream& os) const { os << "(" << _t[0] << ", " << _t[1] << ")"; } static int cmp(Tuple a, Tuple b) {return a.cmp(b);} static double distance(Tuple a, Tuple b) {return a.distance(b);} static double angle(const Tuple& a, const Tuple& b, const Tuple& c) {return b.angle(a, c);} static void angleCheck(const Tuple& a, const Tuple& b, const Tuple& c, bool& ob, bool& sm, double M) { b.angleCheck(a, c, ob, sm, M); } static bool angleGTCheck(const Tuple& a, const Tuple& b, const Tuple& c, double M) { return b.angleGTCheck(a, c, M); } static bool angleOBCheck(const Tuple& a, const Tuple& b, const Tuple& c) { return b.angleOBCheck(a, c); } }; static inline std::ostream& operator<<(std::ostream& os, const Tuple& rhs) { rhs.print(os); return os; } static inline Tuple operator*(double d, Tuple rhs) { return rhs * d; } #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/delaunayrefinement/Verifier.h
/** Delaunay triangulation verifier -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2012, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @section Description * * @author Xin Sui <[email protected]> */ #ifndef VERIFIER_H #define VERIFIER_H #include "Galois/Galois.h" #include "Galois/ParallelSTL/ParallelSTL.h" #include <stack> #include <set> #include <iostream> class Verifier { struct inconsistent: public std::unary_function<GNode,bool> { Graph* graph; inconsistent(Graph* g): graph(g) { } bool operator()(const GNode& node) const { Element& e = graph->getData(node); size_t dist = std::distance(graph->edge_begin(node), graph->edge_end(node)); if (e.dim() == 2) { if (dist != 1) { std::cerr << "Error: Segment " << e << " has " << dist << " relation(s)\n"; return true; } } else if (e.dim() == 3) { if (dist != 3) { std::cerr << "Error: Triangle " << e << " has " << dist << " relation(s)\n"; return true; } } else { std::cerr << "Error: Element with " << e.dim() << " edges\n"; return true; } return false; } }; struct not_delaunay: public std::unary_function<GNode,bool> { Graph* graph; not_delaunay(Graph* g): graph(g) { } bool operator()(const GNode& node) { Element& e1 = graph->getData(node); for (Graph::edge_iterator jj = graph->edge_begin(node), ej = graph->edge_end(node); jj != ej; ++jj) { const GNode& n = graph->getEdgeDst(jj); Element& e2 = graph->getData(n); if (e1.dim() == 3 && e2.dim() == 3) { Tuple t2; if (!getTupleT2OfRelatedEdge(e1, e2, t2)) { std::cerr << "missing tuple\n"; return true; } if (e1.inCircle(t2)) { std::cerr << "Delaunay property violated: point " << t2 << " in element " << e1 << "\n"; return true; } } } return false; } bool getTupleT2OfRelatedEdge(const Element& e1, const Element& e2, Tuple& t) { int e2_0 = -1; int e2_1 = -1; int phase = 0; for (int i = 0; i < e1.dim(); i++) { for (int j = 0; j < e2.dim(); j++) { if (e1.getPoint(i) != e2.getPoint(j)) continue; if (phase == 0) { e2_0 = j; phase = 1; break; } e2_1 = j; for (int k = 0; k < 3; k++) { if (k != e2_0 && k != e2_1) { t = e2.getPoint(k); return true; } } } } return false; } }; bool checkReachability(Graph* graph) { std::stack<GNode> remaining; std::set<GNode> found; remaining.push(*(graph->begin())); while (!remaining.empty()) { GNode node = remaining.top(); remaining.pop(); if (!found.count(node)) { if (!graph->containsNode(node)) { std::cerr << "Reachable node was removed from graph\n"; } found.insert(node); int i = 0; for (Graph::edge_iterator ii = graph->edge_begin(node), ei = graph->edge_end(node); ii != ei; ++ii) { GNode n = graph->getEdgeDst(ii); assert(i < 3); assert(graph->containsNode(n)); assert(node != n); ++i; remaining.push(n); } } } if (found.size() != graph->size()) { std::cerr << "Error: Not all elements are reachable. "; std::cerr << "Found: " << found.size() << " needed: " << graph->size() << ".\n"; return false; } return true; } public: bool verify(Graph* g) { return Galois::ParallelSTL::find_if(g->begin(), g->end(), inconsistent(g)) == g->end() && Galois::ParallelSTL::find_if(g->begin(), g->end(), not_delaunay(g)) == g->end() && checkReachability(g); } }; #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/delaunayrefinement/Mesh.h
/** Delaunay refinement -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2012, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @section Description * * @author Milind Kulkarni <[email protected]> */ #ifndef MESH_H #define MESH_H #include "Subgraph.h" #include <vector> #include <string> #include <map> #include <iostream> #include <cstdio> struct is_bad { Graph* g; is_bad(Graph* _g): g(_g) {} bool operator()(const GNode& n) const { return g->getData(n, Galois::MethodFlag::NONE).isBad(); } }; struct create_nodes { Graph* g; create_nodes(Graph* _g): g(_g) {} void operator()(Element& item) { GNode n = g->createNode(item); g->addNode(n); } }; struct centerXCmp { bool operator()(const Element& lhs, const Element& rhs) const { //return lhs.getCenter() < rhs.getCenter(); return lhs.getPoint(0)[0] < rhs.getPoint(0)[0]; } }; struct centerYCmp { bool operator()(const Element& lhs, const Element& rhs) const { //return lhs.getCenter() < rhs.getCenter(); return lhs.getPoint(0)[1] < rhs.getPoint(0)[1]; } }; struct centerYCmpInv { bool operator()(const Element& lhs, const Element& rhs) const { //return lhs.getCenter() < rhs.getCenter(); return rhs.getPoint(0)[1] < lhs.getPoint(0)[1]; } }; /** * Helper class used providing methods to read in information and create the graph * */ class Mesh { std::vector<Element> elements; size_t id; private: void checkResults(int act, int exp, std::string& str) { if (act != exp) { std::cerr << "Failed read in " << str << "\n"; abort(); } } bool readNodesBin(std::string filename, std::vector<Tuple>& tuples) { FILE* pFile = fopen(filename.append(".node.bin").c_str(), "r"); if (!pFile) { return false; } std::cout << "Using bin for node\n"; uint32_t ntups[4]; if (fread(&ntups[0], sizeof(uint32_t), 4, pFile) < 4) { std::cerr << "Malformed binary file\n"; abort(); } tuples.resize(ntups[0]); for (size_t i = 0; i < ntups[0]; i++) { struct record { uint32_t index; double x, y, z; }; record R; if (fread(&R, sizeof(record), 1, pFile) < 1) { std::cerr << "Malformed binary file\n"; abort(); } tuples[R.index] = Tuple(R.x,R.y); } fclose(pFile); return true; } void readNodes(std::string filename, std::vector<Tuple>& tuples) { if (readNodesBin(filename, tuples)) return; else writeNodes(filename); FILE* pFile = fopen(filename.append(".node").c_str(), "r"); if (!pFile) { std::cerr << "Failed to load file " << filename << "\n"; abort(); } unsigned ntups; int r = fscanf(pFile, "%u %*u %*u %*u", &ntups); checkResults(r, 1, filename); tuples.resize(ntups); for (size_t i = 0; i < ntups; i++) { unsigned index; double x, y; r = fscanf(pFile, "%u %lf %lf %*f", &index, &x, &y); checkResults(r, 3, filename); tuples[index] = Tuple(x,y); } fclose(pFile); } void writeNodes(std::string filename) { std::string filename2 = filename; FILE* pFile = fopen(filename.append(".node").c_str(), "r"); FILE* oFile = fopen(filename2.append(".node.bin").c_str(), "w"); if (!pFile) { std::cerr << "Failed to load file " << filename << " (continuing)\n"; return; } if (!oFile) { std::cerr << "Failed to open file " << filename2 << " (continuing)\n"; return; } unsigned ntups[4]; int r = fscanf(pFile, "%u %u %u %u", &ntups[0], &ntups[1], &ntups[2], &ntups[3]); checkResults(r, 4, filename); uint32_t ntups32[4] = {ntups[0], ntups[1], ntups[2], ntups[3]}; fwrite(&ntups32[0], sizeof(uint32_t), 4, oFile); for (size_t i = 0; i < ntups[0]; i++) { struct record { unsigned index; double x, y, z; }; struct recordOut { uint32_t index; double x, y, z; }; record R; r = fscanf(pFile, "%u %lf %lf %lf", &R.index, &R.x, &R.y, &R.z); checkResults(r, 4, filename); recordOut R2 = {R.index, R.x, R.y, R.z}; fwrite(&R2, sizeof(recordOut), 1, oFile); } fclose(pFile); fclose(oFile); } bool readElementsBin(std::string filename, std::vector<Tuple>& tuples) { FILE* pFile = fopen(filename.append(".ele.bin").c_str(), "r"); if (!pFile) { return false; } std::cout << "Using bin for ele\n"; uint32_t nels[3]; if (fread(&nels[0], sizeof(uint32_t), 3, pFile) < 3) { std::cerr << "Malformed binary file\n"; abort(); } for (size_t i = 0; i < nels[0]; i++) { uint32_t r[4]; if (fread(&r[0], sizeof(uint32_t), 4, pFile) < 4) { std::cerr << "Malformed binary file\n"; abort(); } assert(r[1] < tuples.size()); assert(r[2] < tuples.size()); assert(r[3] < tuples.size()); Element e(tuples[r[1]], tuples[r[2]], tuples[r[3]], ++id); elements.push_back(e); } fclose(pFile); return true; } void readElements(std::string filename, std::vector<Tuple>& tuples) { if (readElementsBin(filename, tuples)) return; else writeElements(filename); FILE* pFile = fopen(filename.append(".ele").c_str(), "r"); if (!pFile) { std::cerr << "Failed to load file " << filename << "\n"; abort(); } unsigned nels; int r = fscanf(pFile, "%u %*u %*u", &nels); checkResults(r, 1, filename); for (size_t i = 0; i < nels; i++) { unsigned index; unsigned n1, n2, n3; r = fscanf(pFile, "%u %u %u %u", &index, &n1, &n2, &n3); checkResults(r, 4, filename); assert(n1 < tuples.size()); assert(n2 < tuples.size()); assert(n3 < tuples.size()); Element e(tuples[n1], tuples[n2], tuples[n3], ++id); elements.push_back(e); } fclose(pFile); } void writeElements(std::string filename) { std::string filename2 = filename; FILE* pFile = fopen(filename.append(".ele").c_str(), "r"); FILE* oFile = fopen(filename2.append(".ele.bin").c_str(), "w"); if (!pFile) { std::cerr << "Failed to load file " << filename << " (continuing)\n"; return; } if (!oFile) { std::cerr << "Failed to open file " << filename2 << " (continuing)\n"; return; } unsigned nels[3]; int r = fscanf(pFile, "%u %u %u", &nels[0], &nels[1], &nels[2]); checkResults(r, 3, filename); uint32_t nels32[3] = {nels[0], nels[1], nels[2]}; fwrite(&nels32[0], sizeof(uint32_t), 3, oFile); for (size_t i = 0; i < nels[0]; i++) { unsigned index; unsigned n1, n2, n3; r = fscanf(pFile, "%u %u %u %u", &index, &n1, &n2, &n3); checkResults(r, 4, filename); uint32_t vals[4] = {index, n1, n2, n3}; fwrite(&vals[0], sizeof(uint32_t), 4, oFile); } fclose(pFile); fclose(oFile); } bool readPolyBin(std::string filename, std::vector<Tuple>& tuples) { FILE* pFile = fopen(filename.append(".poly.bin").c_str(), "r"); if (!pFile) { return false; } std::cout << "Using bin for poly\n"; uint32_t nsegs[4]; if (fread(&nsegs[0], sizeof(uint32_t), 4, pFile) < 4) { std::cerr << "Malformed binary file\n"; abort(); } if (fread(&nsegs[0], sizeof(uint32_t), 2, pFile) < 2) { std::cerr << "Malformed binary file\n"; abort(); } for (size_t i = 0; i < nsegs[0]; i++) { uint32_t r[4]; if (fread(&r[0], sizeof(uint32_t), 4, pFile) < 4) { std::cerr << "Malformed binary file\n"; abort(); } assert(r[1] < tuples.size()); assert(r[2] < tuples.size()); Element e(tuples[r[1]], tuples[r[2]], ++id); elements.push_back(e); } fclose(pFile); return true; } void readPoly(std::string filename, std::vector<Tuple>& tuples) { if (readPolyBin(filename, tuples)) return; else writePoly(filename); FILE* pFile = fopen(filename.append(".poly").c_str(), "r"); if (!pFile) { std::cerr << "Failed to load file " << filename << "\n"; abort(); } unsigned nsegs; int r = fscanf(pFile, "%*u %*u %*u %*u"); checkResults(r, 0, filename); r = fscanf(pFile, "%u %*u", &nsegs); checkResults(r, 1, filename); for (size_t i = 0; i < nsegs; i++) { unsigned index, n1, n2; r = fscanf(pFile, "%u %u %u %*u", &index, &n1, &n2); checkResults(r, 3, filename); assert(n1 < tuples.size()); assert(n2 < tuples.size()); Element e(tuples[n1], tuples[n2], ++id); elements.push_back(e); } fclose(pFile); } void writePoly(std::string filename) { std::string filename2 = filename; FILE* pFile = fopen(filename.append(".poly").c_str(), "r"); FILE* oFile = fopen(filename2.append(".poly.bin").c_str(), "w"); if (!pFile) { std::cerr << "Failed to load file " << filename << " (continuing)\n"; return; } if (!oFile) { std::cerr << "Failed to open file " << filename2 << " (continuing)\n"; return; } unsigned nsegs[4]; int r = fscanf(pFile, "%u %u %u %u", &nsegs[0], &nsegs[1], &nsegs[2], &nsegs[3]); checkResults(r, 4, filename); uint32_t nsegs32[4] = {nsegs[0], nsegs[1], nsegs[2], nsegs[3]}; fwrite(&nsegs32[0], sizeof(uint32_t), 4, oFile); r = fscanf(pFile, "%u %u", &nsegs[0], &nsegs[1]); checkResults(r, 2, filename); nsegs32[0] = nsegs[0]; nsegs32[1] = nsegs[1]; fwrite(&nsegs32[0], sizeof(uint32_t), 2, oFile); for (size_t i = 0; i < nsegs[0]; i++) { unsigned index, n1, n2, n3; r = fscanf(pFile, "%u %u %u %u", &index, &n1, &n2, &n3); checkResults(r, 4, filename); uint32_t r[4] = {index, n1, n2, n3}; fwrite(&r[0], sizeof(uint32_t), 4, oFile); } fclose(pFile); fclose(oFile); } void addElement(Graph* mesh, GNode node, std::map<Edge, GNode>& edge_map) { Element& element = mesh->getData(node); for (int i = 0; i < element.numEdges(); i++) { Edge edge = element.getEdge(i); if (edge_map.find(edge) == edge_map.end()) { edge_map[edge] = node; } else { mesh->addEdge(node, edge_map[edge], Galois::MethodFlag::NONE); edge_map.erase(edge); } } } template<typename Iter> void divide(const Iter& b, const Iter& e) { if (std::distance(b,e) > 16) { std::sort(b,e, centerXCmp()); Iter m = Galois::split_range(b,e); std::sort(b,m, centerYCmpInv()); std::sort(m,e, centerYCmp()); divide(b, Galois::split_range(b,m)); divide(Galois::split_range(b,m), m); divide(m,Galois::split_range(m,e)); divide(Galois::split_range(m,e), e); } } void makeGraph(Graph* mesh, bool parallelAllocate) { //std::sort(elements.begin(), elements.end(), centerXCmp()); divide(elements.begin(), elements.end()); if (parallelAllocate) Galois::do_all(elements.begin(), elements.end(), create_nodes(mesh), Galois::loopname("allocate")); else std::for_each(elements.begin(), elements.end(), create_nodes(mesh)); std::map<Edge, GNode> edge_map; for (Graph::iterator ii = mesh->begin(), ee = mesh->end(); ii != ee; ++ii) addElement(mesh, *ii, edge_map); } public: Mesh(): id(0) { } void read(Graph* mesh, std::string basename, bool parallelAllocate) { std::vector<Tuple> tuples; readNodes(basename, tuples); readElements(basename, tuples); readPoly(basename, tuples); makeGraph(mesh, parallelAllocate); } }; #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/delaunayrefinement/CMakeLists.txt
app(delaunayrefinement)
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/delaunayrefinement/Edge.h
/** Delaunay refinement -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2012, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @section Description * * @author Milind Kulkarni <[email protected]> */ #ifndef EDGE_H #define EDGE_H #include "Tuple.h" class Element; class Edge { Tuple p[2]; public: Edge() {} Edge(const Tuple& a, const Tuple& b) { if (a < b) { p[0] = a; p[1] = b; } else { p[0] = b; p[1] = a; } } Edge(const Edge &rhs) { p[0] = rhs.p[0]; p[1] = rhs.p[1]; } bool operator==(const Edge& rhs) const { return p[0] == rhs.p[0] && p[1] == rhs.p[1]; } bool operator!=(const Edge& rhs) const { return !(*this == rhs); } bool operator<(const Edge& rhs) const { return (p[0] < rhs.p[0]) || ((p[0] == rhs.p[0]) && (p[1] < rhs.p[1])); } bool operator>(const Edge& rhs) const { return (p[0] > rhs.p[0]) || ((p[0] == rhs.p[0]) && (p[1] > rhs.p[1])); } Tuple getPoint(int i) const { return p[i]; } }; #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/delaunayrefinement/Cavity.h
/** Delaunay refinement -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2012, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @section Description * * @author Milind Kulkarni <[email protected]> */ #include <vector> #include <algorithm> class Cavity { typedef std::vector<EdgeTuple,Galois::PerIterAllocTy::rebind<EdgeTuple>::other> ConnTy; Tuple center; GNode centerNode; std::vector<GNode,Galois::PerIterAllocTy::rebind<GNode>::other> frontier; // !the cavity itself PreGraph pre; // !what the new elements should look like PostGraph post; // the edge-relations that connect the boundary to the cavity ConnTy connections; Element* centerElement; Graph* graph; int dim; /** * find the node that is opposite the obtuse angle of the element */ GNode getOpposite(GNode node) { assert(std::distance(graph->edge_begin(node), graph->edge_end(node)) == 3); Element& element = graph->getData(node, Galois::MethodFlag::ALL); Tuple elementTuple = element.getObtuse(); Edge ObtuseEdge = element.getOppositeObtuse(); for (Graph::edge_iterator ii = graph->edge_begin(node, Galois::MethodFlag::ALL), ee = graph->edge_end(node, Galois::MethodFlag::ALL); ii != ee; ++ii) { GNode neighbor = graph->getEdgeDst(ii); //Edge& edgeData = graph->getEdgeData(node, neighbor); Edge edgeData = element.getRelatedEdge(graph->getData(neighbor, Galois::MethodFlag::ALL)); if (elementTuple != edgeData.getPoint(0) && elementTuple != edgeData.getPoint(1)) { return neighbor; } } GALOIS_DIE("unreachable"); return node; } void expand(GNode node, GNode next) { Element& nextElement = graph->getData(next, Galois::MethodFlag::ALL); if ((!(dim == 2 && nextElement.dim() == 2 && next != centerNode)) && nextElement.inCircle(center)) { // isMember says next is part of the cavity, and we're not the second // segment encroaching on this cavity if ((nextElement.dim() == 2) && (dim != 2)) { // is segment, and we are encroaching initialize(next); build(); } else { if (!pre.containsNode(next)) { pre.addNode(next); frontier.push_back(next); } } } else { // not a member //Edge& edgeData = graph->getEdgeData(node, next); Edge edgeData = nextElement.getRelatedEdge(graph->getData(node, Galois::MethodFlag::ALL)); EdgeTuple edge(node, next, edgeData); if (std::find(connections.begin(), connections.end(), edge) == connections.end()) { connections.push_back(edge); } } } public: Cavity(Graph* g, Galois::PerIterAllocTy& cnx) :frontier(cnx), pre(cnx), post(cnx), connections(cnx), graph(g) {} void initialize(GNode node) { pre.reset(); post.reset(); connections.clear(); frontier.clear(); centerNode = node; centerElement = &graph->getData(centerNode, Galois::MethodFlag::ALL); while (graph->containsNode(centerNode, Galois::MethodFlag::ALL) && centerElement->isObtuse()) { centerNode = getOpposite(centerNode); centerElement = &graph->getData(centerNode, Galois::MethodFlag::ALL); } center = centerElement->getCenter(); dim = centerElement->dim(); pre.addNode(centerNode); frontier.push_back(centerNode); } void build() { while (!frontier.empty()) { GNode curr = frontier.back(); frontier.pop_back(); for (Graph::edge_iterator ii = graph->edge_begin(curr, Galois::MethodFlag::ALL), ee = graph->edge_end(curr, Galois::MethodFlag::ALL); ii != ee; ++ii) { GNode neighbor = graph->getEdgeDst(ii); expand(curr, neighbor); } } } /** * Create the new cavity based on the data of the old one */ void computePost() { if (centerElement->dim() == 2) { // we built around a segment GNode n1 = graph->createNode(Element(center, centerElement->getPoint(0))); GNode n2 = graph->createNode(Element(center, centerElement->getPoint(1))); post.addNode(n1); post.addNode(n2); } for (ConnTy::iterator ii = connections.begin(), ee = connections.end(); ii != ee; ++ii) { EdgeTuple tuple = *ii; Element newElement(center, tuple.data.getPoint(0), tuple.data.getPoint(1)); GNode other = pre.containsNode(tuple.dst) ? tuple.src : tuple.dst; Element& otherElement = graph->getData(other, Galois::MethodFlag::ALL); GNode newNode = graph->createNode(newElement); // XXX const Edge& otherEdge = newElement.getRelatedEdge(otherElement); post.addEdge(newNode, other, otherEdge); for (PostGraph::iterator ii = post.begin(), ee = post.end(); ii != ee; ++ii) { GNode node = *ii; Element& element = graph->getData(node, Galois::MethodFlag::ALL); if (element.isRelated(newElement)) { const Edge& edge = newElement.getRelatedEdge(element); post.addEdge(newNode, node, edge); } } post.addNode(newNode); } } void update(GNode node, Galois::UserContext<GNode>& ctx) { for (PreGraph::iterator ii = pre.begin(), ee = pre.end(); ii != ee; ++ii) graph->removeNode(*ii, Galois::MethodFlag::NONE); //add new data for (PostGraph::iterator ii = post.begin(), ee = post.end(); ii != ee; ++ii) { GNode n = *ii; graph->addNode(n, Galois::MethodFlag::NONE); Element& element = graph->getData(n, Galois::MethodFlag::NONE); if (element.isBad()) { ctx.push(n); } } for (PostGraph::edge_iterator ii = post.edge_begin(), ee = post.edge_end(); ii != ee; ++ii) { EdgeTuple edge = *ii; graph->addEdge(edge.src, edge.dst, Galois::MethodFlag::NONE); } if (graph->containsNode(node, Galois::MethodFlag::NONE)) { ctx.push(node); } } };
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/delaunayrefinement/Subgraph.h
/** Delaunay refinement -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2012, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @section Description * * @author Milind Kulkarni <[email protected]> */ #ifndef SUBGRAPH_H #define SUBGRAPH_H #include "Element.h" #include "Galois/Galois.h" #include "Galois/Graph/Graph.h" #include <vector> #include <algorithm> typedef Galois::Graph::FirstGraph<Element,void,false> Graph; typedef Graph::GraphNode GNode; struct EdgeTuple { GNode src; GNode dst; Edge data; EdgeTuple(GNode s, GNode d, const Edge& _d):src(s), dst(d), data(_d) {} bool operator==(const EdgeTuple& rhs) const { return src == rhs.src && dst == rhs.dst && data == data; } }; /** * A sub-graph of the mesh. Used to store information about the original * cavity */ class PreGraph { typedef std::vector<GNode,Galois::PerIterAllocTy::rebind<GNode>::other> NodesTy; NodesTy nodes; public: typedef NodesTy::iterator iterator; explicit PreGraph(Galois::PerIterAllocTy& cnx): nodes(cnx) {} bool containsNode(GNode N) { return std::find(nodes.begin(), nodes.end(), N) != nodes.end(); } void addNode(GNode n) { return nodes.push_back(n); } void reset() { nodes.clear(); } iterator begin() { return nodes.begin(); } iterator end() { return nodes.end(); } }; /** * A sub-graph of the mesh. Used to store information about the original * and updated cavity */ class PostGraph { struct TempEdge { size_t src; GNode dst; Edge edge; TempEdge(size_t s, GNode d, const Edge& e): src(s), dst(d), edge(e) { } }; typedef std::vector<GNode,Galois::PerIterAllocTy::rebind<GNode>::other> NodesTy; typedef std::vector<EdgeTuple,Galois::PerIterAllocTy::rebind<EdgeTuple>::other> EdgesTy; //! the nodes in the graph before updating NodesTy nodes; //! the edges that connect the subgraph to the rest of the graph EdgesTy edges; public: typedef NodesTy::iterator iterator; typedef EdgesTy::iterator edge_iterator; explicit PostGraph(Galois::PerIterAllocTy& cnx): nodes(cnx), edges(cnx) { } void addNode(GNode n) { nodes.push_back(n); } void addEdge(GNode src, GNode dst, const Edge& e) { edges.push_back(EdgeTuple(src, dst, e)); } void reset() { nodes.clear(); edges.clear(); } iterator begin() { return nodes.begin(); } iterator end() { return nodes.end(); } edge_iterator edge_begin() { return edges.begin(); } edge_iterator edge_end() { return edges.end(); } }; #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/delaunayrefinement/DelaunayRefinement.cpp
/** Delaunay refinement -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2012, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @section Description * * Refinement of an initial, unrefined Delaunay mesh to eliminate triangles * with angles < 30 degrees, using a variation of Chew's algorithm. * * @author Milind Kulkarni <[email protected]> * @author Andrew Lenharth <[email protected]> */ #include "Mesh.h" #include "Cavity.h" #include "Verifier.h" #include "Galois/Galois.h" #include "Galois/ParallelSTL/ParallelSTL.h" #include "Galois/Bag.h" #include "Galois/Statistic.h" #include "llvm/Support/CommandLine.h" #include "Lonestar/BoilerPlate.h" #include <iostream> #include <string.h> #include <cassert> namespace cll = llvm::cl; static const char* name = "Delaunay Mesh Refinement"; static const char* desc = "Refines a Delaunay triangulation mesh such that no angle in the mesh is less than 30 degrees"; static const char* url = "delaunay_mesh_refinement"; static cll::opt<std::string> filename(cll::Positional, cll::desc("<input file>"), cll::Required); Graph* graph; enum DetAlgo { nondet, detBase, detPrefix, detDisjoint }; static cll::opt<DetAlgo> detAlgo(cll::desc("Deterministic algorithm:"), cll::values( clEnumVal(nondet, "Non-deterministic"), clEnumVal(detBase, "Base execution"), clEnumVal(detPrefix, "Prefix execution"), clEnumVal(detDisjoint, "Disjoint execution"), clEnumValEnd), cll::init(nondet)); template<int Version=detBase> struct Process { typedef int tt_needs_per_iter_alloc; struct LocalState { Cavity cav; LocalState(Process<Version>& self, Galois::PerIterAllocTy& alloc): cav(graph, alloc) { } }; typedef LocalState GaloisDeterministicLocalState; static_assert(Galois::has_deterministic_local_state<Process>::value, "Oops"); void operator()(GNode item, Galois::UserContext<GNode>& ctx) { if (!graph->containsNode(item, Galois::MethodFlag::ALL)) return; Cavity* cavp = NULL; if (Version == detDisjoint) { bool used; LocalState* localState = (LocalState*) ctx.getLocalState(used); if (used) { localState->cav.update(item, ctx); return; } else { cavp = &localState->cav; } } if (Version == detDisjoint) { cavp->initialize(item); cavp->build(); cavp->computePost(); } else { Cavity cav(graph, ctx.getPerIterAlloc()); cav.initialize(item); cav.build(); cav.computePost(); if (Version == detPrefix) return; cav.update(item, ctx); } } }; struct Preprocess { Galois::InsertBag<GNode>& wl; Preprocess(Galois::InsertBag<GNode>& w): wl(w) { } void operator()(GNode item) const { if (graph->getData(item, Galois::MethodFlag::NONE).isBad()) wl.push(item); } }; struct DetLessThan { bool operator()(const GNode& a, const GNode& b) const { int idA = graph->getData(a, Galois::MethodFlag::NONE).getId(); int idB = graph->getData(b, Galois::MethodFlag::NONE).getId(); if (idA == 0 || idB == 0) abort(); return idA < idB; } }; int main(int argc, char** argv) { Galois::StatManager statManager; LonestarStart(argc, argv, name, desc, url); graph = new Graph(); { Mesh m; m.read(graph, filename.c_str(), detAlgo == nondet); Verifier v; if (!skipVerify && !v.verify(graph)) { GALOIS_DIE("bad input mesh"); } } std::cout << "configuration: " << std::distance(graph->begin(), graph->end()) << " total triangles, " << std::count_if(graph->begin(), graph->end(), is_bad(graph)) << " bad triangles\n"; Galois::reportPageAlloc("MeminfoPre1"); Galois::preAlloc(Galois::Runtime::MM::numPageAllocTotal() * 10); //Galois::preAlloc(15 * numThreads + Galois::Runtime::MM::numPageAllocTotal() * 10); Galois::reportPageAlloc("MeminfoPre2"); Galois::StatTimer T; T.start(); Galois::InsertBag<GNode> initialBad; if (detAlgo == nondet) Galois::do_all_local(*graph, Preprocess(initialBad), Galois::loopname("findbad")); else std::for_each(graph->begin(), graph->end(), Preprocess(initialBad)); Galois::reportPageAlloc("MeminfoMid"); Galois::StatTimer Trefine("refine"); Trefine.start(); using namespace Galois::WorkList; typedef LocalQueue<dChunkedLIFO<256>, ChunkedLIFO<256> > BQ; typedef AltChunkedLIFO<32> Chunked; switch (detAlgo) { case nondet: Galois::for_each_local(initialBad, Process<>(), Galois::loopname("refine"), Galois::wl<Chunked>()); case detBase: Galois::for_each_det(initialBad.begin(), initialBad.end(), Process<>()); break; case detPrefix: Galois::for_each_det(initialBad.begin(), initialBad.end(), Process<detPrefix>(), Process<>()); break; case detDisjoint: Galois::for_each_det(initialBad.begin(), initialBad.end(), Process<detDisjoint>()); break; default: std::cerr << "Unknown algorithm" << detAlgo << "\n"; abort(); } Trefine.stop(); T.stop(); Galois::reportPageAlloc("MeminfoPost"); if (!skipVerify) { int size = Galois::ParallelSTL::count_if(graph->begin(), graph->end(), is_bad(graph)); if (size != 0) { GALOIS_DIE("Bad triangles remaining"); } Verifier v; if (!v.verify(graph)) { GALOIS_DIE("Refinement failed"); } std::cout << std::distance(graph->begin(), graph->end()) << " total triangles\n"; std::cout << "Refinement OK\n"; } return 0; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps
rapidsai_public_repos/code-share/maxflow/galois/apps/des/CMakeLists.txt
file(GLOB Sources ./*.cpp ./common/*.cpp ./logic/*.cpp ) app(DESunorderedSerial unordered/DESunorderedSerial.cpp ${Sources}) app(DESunordered unordered/DESunordered.cpp ${Sources}) app(DESorderedSerial ordered/DESorderedSerial.cpp ${Sources}) app(DESordered ordered/DESordered.cpp ${Sources}) app(DESorderedHand ordered/DESorderedHand.cpp ${Sources}) app(DESorderedHandNB ordered/DESorderedHandNB.cpp ${Sources}) app(DESorderedHandSet ordered/DESorderedHandSet.cpp ${Sources}) include_directories(.) include_directories(./common) include_directories(./logic) include_directories(./ordered) include_directories(./unordered)
0
rapidsai_public_repos/code-share/maxflow/galois/apps/des
rapidsai_public_repos/code-share/maxflow/galois/apps/des/logic/BasicPort.h
/** OneInputGate implements the basic structure of a one input logic gate -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author M. Amber Hassaan <[email protected]> */ #ifndef DES_BASIC_PORT_H #define DES_BASIC_PORT_H #include <string> #include "LogicFunctions.h" #include "OneInputGate.h" namespace des { class BasicPort: public OneInputGate { private: static const BUF& BUFFER; public: BasicPort (const std::string& outputName, const std::string& inputName) : OneInputGate (BUFFER, outputName, inputName) {} BasicPort* makeClone () const { return new BasicPort (*this); } }; } // namespace des #endif // DES_BASIC_PORT_H
0
rapidsai_public_repos/code-share/maxflow/galois/apps/des
rapidsai_public_repos/code-share/maxflow/galois/apps/des/logic/NetlistParser.h
/** NetlistParser reads a circuit netlist containing logic gates and wires etc -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * Created on: Jun 23, 2011 * * @author M. Amber Hassaan <[email protected]> */ #ifndef DES_NETLISTPARSER_H_ #define DES_NETLISTPARSER_H_ #include <vector> #include <string> #include <map> #include <set> #include <iostream> #include <fstream> #include <algorithm> #include <utility> #include <boost/utility.hpp> #include <cstring> #include <cassert> #include <cstdio> #include "comDefs.h" #include "logicDefs.h" #include "LogicFunctions.h" #include "LogicGate.h" #include "OneInputGate.h" #include "TwoInputGate.h" #include "BasicPort.h" namespace des { /** * NetlistTokenizer is a simple string tokenizer, which * usings C strtok () function from <pre>cstring</pre> */ class NetlistTokenizer: public boost::noncopyable { /** * correct way to use is to first check if hasMoreTokens and then call nextToken * * need to read one token ahead so because hasMoreTokens is called before nextToken * * basic algorithm * * initially currTokPtr = NULL, nextTokPtr = nextTokenInt * * In nextToken * return string at currTokPtr * currTokPtr = nextTokPtr * nextTokPtr = read next token * * algorithm for reading next token * read next token (with NULL) * while next token is null or beginning of comment { * read next line (break out the loop if file has ended) * read first token * } * create a string and return * * things to check for * - end of file, reading error (in this case getNextLine() should return NULL) * * initialization: * - initially nextTokPtr should be NULL and this fine because * reading nextTok with null should return null; * */ private: /** file handle for input stream */ std::ifstream ifs; /** what characters mark end of a token */ const char* delim; /** string representing beginning of a line comment */ const char* comments; /** current line read from the file */ char* linePtr; /** ptr to next token */ char* nextTokPtr; /** ptr to current token, returned on a call to nextToken () */ //char* currTokPtr; private: /** * @returns true if nextTokPtr starts with comment pattern */ bool isCommentBegin () const { std::string tok(nextTokPtr); if (tok.find (comments) == 0) { return true; } else { return false; } } /** * read next line from the file * and return it as a C string */ char* getNextLine () { // read next line std::string currLine; if (ifs.eof () || ifs.bad ()) { linePtr = NULL; } else { std::getline (ifs, currLine); delete[] linePtr; linePtr = new char[currLine.size () + 1]; strcpy (linePtr, currLine.c_str ()); } return linePtr; } /** * read next token as a C string */ char* readNextToken () { nextTokPtr = strtok (NULL, delim); while (nextTokPtr == NULL || isCommentBegin ()) { linePtr = getNextLine (); if (linePtr == NULL) { nextTokPtr = NULL; break; } nextTokPtr = strtok (linePtr, delim); } return nextTokPtr; } public: /** * Constructor * * @param fileName: the file to read from * @param delim: a string containing characters that mark end of a token * @param comments: a string that contains beginning of a comment */ NetlistTokenizer (const char* fileName, const char* delim, const char* comments) : ifs(fileName), delim (delim), comments(comments), linePtr (NULL) { if (!ifs.good ()) { std::cerr << "Failed to open this file for reading: " << fileName << std::endl; abort (); } nextTokPtr = readNextToken(); } /** * returns the next token from the file */ const std::string nextToken () { assert (nextTokPtr != NULL); std::string retval(nextTokPtr); nextTokPtr = readNextToken (); return retval; } bool hasMoreTokens () const { return !ifs.eof() || nextTokPtr != NULL; } }; /** * The Class NetlistParser parses an input netlist file. */ class NetlistParser { public: /** following is the list of token separators; characters meant to be ignored */ static const char* DELIM; /** beginning of a comment string */ static const char* COMMENTS; public: typedef std::map<std::string, std::vector<std::pair<SimTime, LogicVal> > > StimulusMapType; private: /** The netlist file. */ const std::string& netlistFile; /** The input names. */ std::vector<std::string> inputNames; /** input ports */ std::vector<BasicPort*> inputPorts; /** The output names. */ std::vector<std::string> outputNames; /** output ports */ std::vector<BasicPort*> outputPorts; /** The out values. */ std::map<std::string, LogicVal> outValues; /** The input stimulus map has a list of (time, value) pairs for each input. */ StimulusMapType inputStimulusMap; /** The gates. */ std::vector<LogicGate*> gates; /** The finish time. */ SimTime finishTime; private: /** * A mapping from string name (in the netlist) to functor that implements * the corresponding functionality. Helps in initialization */ static const std::map<std::string, OneInputFunc* >& oneInputGates () { static std::map<std::string, OneInputFunc*> oneInMap; oneInMap.insert(std::make_pair (toLowerCase ("INV"), new INV())); return oneInMap; } /** * A mapping from string name (in the netlist) to functor that implements * the corresponding functionality. Helps in initialization */ static const std::map<std::string, TwoInputFunc*>& twoInputGates () { static std::map<std::string, TwoInputFunc*> twoInMap; twoInMap.insert(std::make_pair (toLowerCase ("AND2") , new AND2())); twoInMap.insert(std::make_pair (toLowerCase ("NAND2") , new NAND2())); twoInMap.insert(std::make_pair (toLowerCase ("OR2") , new OR2())); twoInMap.insert(std::make_pair (toLowerCase ("NOR2") , new NOR2())); twoInMap.insert(std::make_pair (toLowerCase ("XOR2") , new XOR2())); twoInMap.insert(std::make_pair (toLowerCase ("XNOR2") , new XNOR2())); return twoInMap; } /** * Parses the port list i.e. inputs and outputs * * @param tokenizer the tokenizer * @param portNames the net names for input/output ports */ static void parsePortList(NetlistTokenizer& tokenizer, std::vector<std::string>& portNames) { std::string token = toLowerCase (tokenizer.nextToken ()); while (token != ("end")) { portNames.push_back(token); token = toLowerCase (tokenizer.nextToken ()); } } static const char* getInPrefix () { return "in_"; } static const char* getOutPrefix () { return "out_"; } void createInputPorts () { for (std::vector<std::string>::const_iterator i = inputNames.begin (), ei = inputNames.end (); i != ei; ++i) { const std::string& out = *i; std::string in = getInPrefix() + out; inputPorts.push_back (new BasicPort (out, in)); } } void createOutputPorts () { for (std::vector<std::string>::const_iterator i = outputNames.begin (), ei = outputNames.end (); i != ei; ++i) { const std::string& in = *i; std::string out = getOutPrefix() + in; outputPorts.push_back (new BasicPort (out, in)); } } /** * Parses the out values, which are the expected values of the circuit outputs at the end of * simulation * * @param tokenizer the tokenizer * @param outValues the expected out values at the end of the simulation */ static void parseOutValues(NetlistTokenizer& tokenizer, std::map<std::string, LogicVal>& outValues) { std::string token = toLowerCase (tokenizer.nextToken ()); while (token != ("end")) { std::string outName = token; token = toLowerCase (tokenizer.nextToken ()); LogicVal value = token[0]; token = toLowerCase (tokenizer.nextToken ()); outValues.insert (std::make_pair(outName, value)); } } /** * Parses the initialization list for all the inputs. * * @param tokenizer the tokenizer * @param inputStimulusMap the input stimulus map */ static void parseInitList(NetlistTokenizer& tokenizer, StimulusMapType& inputStimulusMap) { // capture the name of the input signal std::string input = toLowerCase (tokenizer.nextToken ()); std::string token = toLowerCase (tokenizer.nextToken ()); std::vector<std::pair<SimTime, LogicVal> > timeValList; while (token != ("end")) { SimTime t(atol (token.c_str ())); // SimTime.parseLong(token); token = toLowerCase (tokenizer.nextToken ()); LogicVal v = token[0]; timeValList.push_back (std::make_pair(t, v)); token = toLowerCase (tokenizer.nextToken ()); } inputStimulusMap.insert (std::make_pair(input, timeValList)); } /** * Parses the actual list of gates * * @param tokenizer the tokenizer * @param gates the gates */ static void parseNetlist(NetlistTokenizer& tokenizer, std::vector<LogicGate*>& gates) { std::string token = toLowerCase (tokenizer.nextToken ()); while (token != ("end")) { if (oneInputGates().count (token) > 0) { const OneInputFunc* func = (oneInputGates ().find (token))->second; std::string outputName = toLowerCase (tokenizer.nextToken ()); // output name std::string inputName = toLowerCase (tokenizer.nextToken ()); // input OneInputGate* g = new OneInputGate (*func, outputName, inputName); gates.push_back (g); // possibly delay, if no delay then next gate or end token = toLowerCase (tokenizer.nextToken ()); if (token[0] == '#') { token = token.substr(1); SimTime d(atol (token.c_str ())); // SimTime.parseLong(token); g->setDelay(d); } else { continue; } } else if (twoInputGates().count (token) > 0) { const TwoInputFunc* func = (twoInputGates ().find (token))->second; std::string outputName = toLowerCase (tokenizer.nextToken ()); // output name std::string input1Name = toLowerCase (tokenizer.nextToken ()); // input 1 std::string input2Name = toLowerCase (tokenizer.nextToken ()); // input 2 TwoInputGate* g = new TwoInputGate (*func, outputName, input1Name, input2Name); gates.push_back (g); // possibly delay, if no delay then next gate or end token = toLowerCase (tokenizer.nextToken ()); if (token[0] == '#') { token = token.substr(1); SimTime d(atol (token.c_str ())); // SimTime.parseLong(token); g->setDelay(d); } else { continue; } } else { std::cerr << "Unknown type of gate " << token << std::endl; abort (); } //necessary to move forward in the while loop token = toLowerCase (tokenizer.nextToken ()); } // end of while } /** * Parses the netlist contained in fileName. * * Parsing steps * parse input signal names * parse output signal names * parse finish time * parse stimulus lists for each input signal * parse the netlist * * @param fileName the file name */ void parse(const std::string& fileName) { std::cout << "input: reading circuit from file: " << fileName << std::endl; NetlistTokenizer tokenizer (fileName.c_str (), DELIM, COMMENTS); std::string token; while (tokenizer.hasMoreTokens()) { token = toLowerCase (tokenizer.nextToken ()); if (token == ("inputs")) { parsePortList(tokenizer, inputNames); } else if (token == ("outputs")) { parsePortList(tokenizer, outputNames); } else if (token == ("outvalues")) { parseOutValues(tokenizer, outValues); } else if (token == ("finish")) { token = toLowerCase (tokenizer.nextToken ()); finishTime = SimTime (atol (token.c_str ())); // SimTime.parseLong(token); } else if (token == ("initlist")) { parseInitList(tokenizer, inputStimulusMap); } else if (token == ("netlist")) { parseNetlist(tokenizer, gates); } } // end outer while createInputPorts (); createOutputPorts (); } // end parse() void destroy () { destroyVec (gates); } public: /** * Instantiates a new netlist parser. * * @param netlistFile the netlist file */ NetlistParser(const std::string& netlistFile): netlistFile(netlistFile) { parse(netlistFile); } ~NetlistParser () { destroy (); } /** * Gets the finish time. * * @return the finish time */ const SimTime& getFinishTime() const { return finishTime; } /** * Gets the netlist file. * * @return the netlist file */ const std::string& getNetlistFile() const { return netlistFile; } /** * Gets the input names. * * @return the input names */ const std::vector<std::string>& getInputNames() const { return inputNames; } /** * * @return input ports vector */ const std::vector<BasicPort*>& getInputPorts () const { return inputPorts; } /** * Gets the output names. * * @return the output names */ const std::vector<std::string>& getOutputNames() const { return outputNames; } /** * * @return output ports vector */ const std::vector<BasicPort*>& getOutputPorts () const { return outputPorts; } /** * Gets the out values. * * @return the out values */ const std::map<std::string, LogicVal>& getOutValues() const { return outValues; } /** * Gets the input stimulus map. * * @return the input stimulus map */ const StimulusMapType& getInputStimulusMap() const { return inputStimulusMap; } /** * Gets the gates. * * @return the gates */ const std::vector<LogicGate*>& getGates() const { return gates; } }; } // namespace des #endif /* DES_NETLISTPARSER_H_ */
0
rapidsai_public_repos/code-share/maxflow/galois/apps/des
rapidsai_public_repos/code-share/maxflow/galois/apps/des/logic/NetlistParser.cpp
#include "NetlistParser.h" const char* des::NetlistParser::DELIM = " \n\t,;()="; const char* des::NetlistParser::COMMENTS = "//";
0
rapidsai_public_repos/code-share/maxflow/galois/apps/des
rapidsai_public_repos/code-share/maxflow/galois/apps/des/logic/logicDefs.h
/** Some common definitions and helper functions -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author M. Amber Hassaan <[email protected]> */ #ifndef DES_LOGIC_DEFS_H_ #define DES_LOGIC_DEFS_H_ namespace des { /** type used for value of a signal e.g. 0, 1, X , Z */ typedef char LogicVal; /** the unknown logic value */ const char LOGIC_UNKNOWN = 'X'; const char LOGIC_ZERO = '0'; const char LOGIC_ONE = '1'; } // namespace des #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps/des
rapidsai_public_repos/code-share/maxflow/galois/apps/des/logic/LogicFunctions.h
/** Defines the basic functors for one and two input logic gates -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author M. Amber Hassaan <[email protected]> */ #ifndef DES_LOGIC_FUNCTIONS_H_ #define DES_LOGIC_FUNCTIONS_H_ #include <functional> #include <string> #include "logicDefs.h" namespace des { /** * LogicFunc is a functor, serving as a common base type * for one and two input functors. */ struct LogicFunc { virtual const std::string str () const = 0; }; /** * Interface of a functor for modeling the funciton of a one input one, output logic gate. * Each implementation of this interface is a different kind of one input gate, e.g. an * inverter, buffer etc */ struct OneInputFunc: public LogicFunc { virtual LogicVal operator () (const LogicVal& in) const = 0; }; /** * Interface of a functor for modeling functionality a logic gate with two inputs and one output. * Each implementation of this interface describes a two input gate */ struct TwoInputFunc: public LogicFunc { virtual LogicVal operator () (const LogicVal& x, const LogicVal& y) const = 0; }; /** * Buffer */ struct BUF : public OneInputFunc, public std::unary_function<LogicVal, LogicVal> { LogicVal _buf_ (const LogicVal& in) const { return in; } virtual LogicVal operator () (const LogicVal& in) const { return _buf_ (in); } virtual const std::string str () const { return "BUF"; } }; /** * Inverter */ struct INV : public OneInputFunc, public std::unary_function<LogicVal, LogicVal> { LogicVal _not_ (const LogicVal& in) const { if (in == LOGIC_ZERO) { return LOGIC_ONE; } else if (in == LOGIC_ONE) { return LOGIC_ZERO; } else { return LOGIC_UNKNOWN; } } virtual LogicVal operator () (const LogicVal& in) const { return _not_ (in); } virtual const std::string str () const { return "INV"; } }; /** * And with two inputs */ struct AND2: public TwoInputFunc, public std::binary_function<LogicVal, LogicVal, LogicVal> { LogicVal _and_ (const LogicVal& x, const LogicVal& y) const { if (x == LOGIC_ZERO || y == LOGIC_ZERO) { return LOGIC_ZERO; } else if (x == LOGIC_ONE ) { return y; } else if (y == LOGIC_ONE) { return x; } else { return LOGIC_UNKNOWN; } } virtual LogicVal operator () (const LogicVal& x, const LogicVal& y) const { return _and_ (x, y); } virtual const std::string str () const { return "AND2"; } }; /** * Nand with two inputs */ struct NAND2: public AND2 { LogicVal _nand_ (const LogicVal& x, const LogicVal& y) const { return INV()._not_ (AND2::_and_ (x, y)); } virtual LogicVal operator () (const LogicVal& x, const LogicVal& y) const { return _nand_ (x, y); } virtual const std::string str () const { return "NAND2"; } }; /** * OR with two inputs */ struct OR2: public TwoInputFunc, public std::binary_function<LogicVal, LogicVal, LogicVal> { LogicVal _or_ (const LogicVal& x, const LogicVal& y) const { if (x == LOGIC_ONE || y == LOGIC_ONE) { return LOGIC_ONE; } else if (x == LOGIC_ZERO) { return y; } else if (y == LOGIC_ZERO) { return x; } else { return LOGIC_UNKNOWN; } } virtual LogicVal operator () (const LogicVal& x, const LogicVal& y) const { return _or_ (x, y); } virtual const std::string str () const { return "OR2"; } }; /** * NOR with two inputs */ struct NOR2: public OR2 { LogicVal _nor_ (const LogicVal& x, const LogicVal& y) const { return INV()._not_ (OR2::_or_ (x, y)); } virtual LogicVal operator () (const LogicVal& x, const LogicVal& y) const { return _nor_ (x, y); } virtual const std::string str () const { return "NOR2"; } }; /** * XOR with two inputs */ struct XOR2: public TwoInputFunc, public std::binary_function<LogicVal, LogicVal, LogicVal> { LogicVal _xor_ (const LogicVal& x, const LogicVal& y) const { if (x == LOGIC_UNKNOWN || y == LOGIC_UNKNOWN) { return LOGIC_UNKNOWN; } else if (INV()._not_(x) == y) { return LOGIC_ONE; } else if (x == y) { return LOGIC_ZERO; } else { return LOGIC_UNKNOWN; } } virtual LogicVal operator () (const LogicVal& x, const LogicVal& y) const { return _xor_ (x, y); } virtual const std::string str () const { return "XOR2"; } }; /** * XNOR with two inputs */ struct XNOR2: public XOR2 { LogicVal _xnor_ (const LogicVal& x, const LogicVal& y) const { return INV()._not_ (XOR2::_xor_ (x, y) ); } virtual LogicVal operator () (const LogicVal& x, const LogicVal& y) const { return _xnor_ (x, y); } virtual const std::string str () const { return "XNOR2"; } }; } // namespace des #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps/des
rapidsai_public_repos/code-share/maxflow/galois/apps/des/logic/LogicGate.cpp
/** LogicGate implements the basic structure of a logic gate -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author M. Amber Hassaan <[email protected]> */ #include "LogicGate.h"
0
rapidsai_public_repos/code-share/maxflow/galois/apps/des
rapidsai_public_repos/code-share/maxflow/galois/apps/des/logic/OneInputGate.h
/** OneInputGate implements the basic structure of a one input logic gate -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author M. Amber Hassaan <[email protected]> */ #ifndef DES_BASE_ONE_INPUT_GATE_H_ #define DES_BASE_ONE_INPUT_GATE_H_ #include <string> #include <sstream> #include "comDefs.h" #include "logicDefs.h" #include "LogicFunctions.h" #include "LogicGate.h" namespace des { struct OneInputGateTraits { static const size_t N_OUT = 1; static const size_t N_IN = 1; }; class OneInputGate: public BaseLogicGate<OneInputGateTraits::N_OUT, OneInputGateTraits::N_IN> { private: typedef BaseLogicGate<OneInputGateTraits::N_OUT, OneInputGateTraits::N_IN> SuperTy; protected: /** * a functor which computes an output LogicVal when * provided an input LogicVal */ const OneInputFunc& func; /** The input name. */ std::string inputName; /** The input val. */ LogicVal inputVal; public: /** * Instantiates a new one input gate. */ OneInputGate (const OneInputFunc& func, const std::string& outputName, const std::string& inputName, const SimTime& delay = MIN_DELAY) : SuperTy (outputName, LOGIC_ZERO, delay), func (func), inputName (inputName) , inputVal (LOGIC_ZERO) {} virtual OneInputGate* makeClone () const { return new OneInputGate (*this); } /** * Applies the update to internal state e.g. change to some input. Must update the output * if the inputs have changed. */ virtual void applyUpdate (const LogicUpdate& lu) { if (hasInputName (lu.getNetName ())) { inputVal = lu.getNetVal (); } else { SuperTy::netNameMismatch (lu); } this->outputVal = evalOutput (); } /** * Evaluate output based on the current state of the input * * @return the */ virtual LogicVal evalOutput () const { return func (inputVal); } /** * @param net: name of a wire * @return true if has an input with the name equal to 'net' */ virtual bool hasInputName (const std::string& net) const { return (inputName == net); } /** * @param inputName net name * @return index of the input matching the net name provided */ virtual size_t getInputIndex (const std::string& inputName) const { if (this->inputName == (inputName)) { return 0; // since there is only one input } abort (); return -1; // error } /** * @return string representation */ virtual std::string str () const { std::ostringstream ss; ss << func.str () << " output: " << outputName << " = " << outputVal << ", input: " << inputName << " = " << inputVal; return ss.str (); } /** * Gets the input name. * * @return the input name */ const std::string& getInputName () const { return inputName; } /** * Sets the input name. * * @param inputName the new input name */ void setInputName (const std::string& inputName) { this->inputName = inputName; } /** * Gets the input val. * * @return the input val */ const LogicVal& getInputVal () const { return inputVal; } /** * Sets the input val. * * @param inputVal the new input val */ void setInputVal (const LogicVal& inputVal) { this->inputVal = inputVal; } }; } // namespace des #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps/des
rapidsai_public_repos/code-share/maxflow/galois/apps/des/logic/LogicGate.h
/** LogicGate implements the basic structure of a logic gate -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author M. Amber Hassaan <[email protected]> */ #ifndef DES_BASE_LOGIC_GATE_H_ #define DES_BASE_LOGIC_GATE_H_ #include <string> #include <iostream> #include "comDefs.h" #include "logicDefs.h" #include "LogicUpdate.h" namespace des { class LogicGate { public: LogicGate () {} LogicGate (const LogicGate& that) {} virtual ~LogicGate () {} virtual LogicGate* makeClone () const = 0; /** * @return number of inputs */ virtual size_t getNumInputs () const = 0; /** * @return number of outputs */ virtual size_t getNumOutputs () const = 0; /** * @return current output value */ virtual LogicVal getOutputVal () const = 0; /** * @return namem of the output */ virtual const std::string& getOutputName () const = 0; /** * @param update * * applies the update to internal state e.g. change to some input. Must update the output * if the inputs have changed */ virtual void applyUpdate (const LogicUpdate& update) = 0; /** * Evaluate output based on the current state of the input * * @return the */ virtual LogicVal evalOutput() const = 0; /** * @param net: name of a wire * @return true if has an input with the name equal to 'net' */ virtual bool hasInputName(const std::string& net) const = 0; /** * @param inputName net name * @return index of the input matching the net name provided */ virtual size_t getInputIndex (const std::string& inputName) const = 0; /** * @param net: name of a wire * @return true if has an output with the name equal to 'net' */ virtual bool hasOutputName(const std::string& net) const = 0; /** * @return string representation */ virtual std::string str () const = 0; /** * @return delay of the gate */ virtual const SimTime& getDelay() const = 0; /** * @param delay value to set to */ virtual void setDelay (const SimTime& delay) = 0; /** * Handles an erroneous situation, where the net name in * LogicUpdate provided does not match any of the inputs. * * @param le */ virtual void netNameMismatch (const LogicUpdate& le) const = 0; }; template <size_t Nout, size_t Nin> class BaseLogicGate: public LogicGate { protected: /** The output name. */ std::string outputName; /** The output val. */ LogicVal outputVal; /** The delay. */ SimTime delay; public: BaseLogicGate (const std::string& outputName, const LogicVal& outVal, const SimTime& delay) : outputName (outputName), outputVal (outVal) { setDelay (delay); } /** * Gets the delay. * * @return the delay */ virtual const SimTime& getDelay() const { return delay; } /** * Sets the delay. * * @param delay the new delay */ virtual void setDelay(const SimTime& delay) { this->delay = delay; if (this->delay <= 0) { this->delay = MIN_DELAY; } } /** * @return number of inputs */ virtual size_t getNumInputs () const { return Nin; } /** * @return number of outputs */ virtual size_t getNumOutputs () const { return Nout; } /** * @return current output value */ virtual LogicVal getOutputVal () const { return outputVal; } /** * @return namem of the output */ virtual const std::string& getOutputName () const { return outputName; } /** * @param net: name of a wire * @return true if has an output with the name equal to 'net' */ virtual bool hasOutputName(const std::string& net) const { return (outputName == net); } /** * Sets the output name. * * @param outputName the new output name */ void setOutputName(const std::string& outputName) { this->outputName = outputName; } /** * Sets the output val. * * @param outputVal the new output val */ void setOutputVal(const LogicVal& outputVal) { this->outputVal = outputVal; } virtual void netNameMismatch (const LogicUpdate& le) const { std::cerr << "Received logic update : " << le.str () << " with mismatching net name, this = " << str () << std::endl; exit (-1); } }; } // namespace des #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps/des
rapidsai_public_repos/code-share/maxflow/galois/apps/des/logic/BasicPort.cpp
/** OneInputGate implements the basic structure of a one input logic gate -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author M. Amber Hassaan <[email protected]> */ #include "BasicPort.h" const des::BUF& des::BasicPort::BUFFER = des::BUF();
0
rapidsai_public_repos/code-share/maxflow/galois/apps/des
rapidsai_public_repos/code-share/maxflow/galois/apps/des/logic/TwoInputGate.h
/** TwoInputGate is basic structure of a two input gates -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author M. Amber Hassaan <[email protected]> */ #ifndef DES_BASE_TWO_INPUT_GATE_H_ #define DES_BASE_TWO_INPUT_GATE_H_ #include <string> #include <sstream> #include "comDefs.h" #include "logicDefs.h" #include "LogicFunctions.h" #include "LogicGate.h" namespace des { struct TwoInputGateTraits { static const size_t N_OUT = 1; static const size_t N_IN = 2; }; class TwoInputGate: public BaseLogicGate<TwoInputGateTraits::N_OUT, TwoInputGateTraits::N_IN> { private: typedef BaseLogicGate<TwoInputGateTraits::N_OUT, TwoInputGateTraits::N_IN> SuperTy; protected: /** * The functor that computes a value for the output of the gate * when provided with the values of the input */ const TwoInputFunc& func; /** The input1 name. */ std::string input1Name; /** The input2 name. */ std::string input2Name; /** The input1 val. */ LogicVal input1Val; /** The input2 val. */ LogicVal input2Val; public: /** * Instantiates a new two input gate. */ TwoInputGate (const TwoInputFunc& func, const std::string& outputName, const std::string& input1Name, const std::string& input2Name, const SimTime& delay = MIN_DELAY) : SuperTy (outputName, LOGIC_ZERO, delay) , func (func) , input1Name (input1Name) , input2Name (input2Name) , input1Val (LOGIC_ZERO) , input2Val (LOGIC_ZERO) {} virtual TwoInputGate* makeClone () const { return new TwoInputGate (*this); } /** * Applies the update to internal state e.g. change to some input. Must update the output * if the inputs have changed * * @param lu the update */ virtual void applyUpdate (const LogicUpdate& lu) { if (input1Name == (lu.getNetName ())) { input1Val = lu.getNetVal (); } else if (input2Name == (lu.getNetName ())) { input2Val = lu.getNetVal (); } else { SuperTy::netNameMismatch (lu); } // output has been changed // update output immediately // generate events to send to all fanout gates to update their inputs afer delay this->outputVal = evalOutput (); } /** * Evaluate output based on the current state of the input * * @return the */ virtual LogicVal evalOutput () const { return func (input1Val, input2Val); } /** * @param net: name of a wire * @return true if has an input with the name equal to 'net' */ virtual bool hasInputName (const std::string& net) const { return (input1Name == (net) || input2Name == (net)); } /** * @param inputName net name * @return index of the input matching the net name provided */ virtual size_t getInputIndex (const std::string& inputName) const { if (this->input2Name == (inputName)) { return 1; } else if (this->input1Name == (inputName)) { return 0; } else { abort (); return -1; // error } } /** * @return string representation */ virtual std::string str () const { std::ostringstream ss; ss << func.str () << " output: " << outputName << " = " << outputVal << " input1: " << input1Name << " = " << input1Val << " input2: " << input2Name << " = " << input2Val; return ss.str (); } /** * Gets the input1 name. * * @return the input1 name */ const std::string& getInput1Name () const { return input1Name; } /** * Sets the input1 name. * * @param input1Name the new input1 name */ void setInput1Name (const std::string& input1Name) { this->input1Name = input1Name; } /** * Gets the input1 val. * * @return the input1 val */ const LogicVal& getInput1Val () const { return input1Val; } /** * Sets the input1 val. * * @param input1Val the new input1 val */ void setInput1Val (const LogicVal& input1Val) { this->input1Val = input1Val; } /** * Gets the input2 name. * * @return the input2 name */ const std::string& getInput2Name () { return input2Name; } /** * Sets the input2 name. * * @param input2Name the new input2 name */ void setInput2Name (const std::string& input2Name) { this->input2Name = input2Name; } /** * Gets the input2 val. * * @return the input2 val */ const LogicVal& getInput2Val () const { return input2Val; } /** * Sets the input2 val. * * @param input2Val the new input2 val */ void setInput2Val (const LogicVal& input2Val) { this->input2Val = input2Val; } }; } // namespace des #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps/des
rapidsai_public_repos/code-share/maxflow/galois/apps/des/logic/LogicUpdate.h
/** LogicUpdate corresponds to a change in the input or output of a gate -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * Created on: Jun 23, 2011 * * @author M. Amber Hassaan <[email protected]> */ #ifndef DES_LOGICUPDATE_H_ #define DES_LOGICUPDATE_H_ #include <string> #include <sstream> #include "logicDefs.h" namespace des { /** * The Class LogicUpdate is the msg carried by events. represents a change in the value of a net. */ class LogicUpdate { /** The net name. */ const std::string* netName; /** The net val. */ LogicVal netVal; public: /** * Instantiates a new logi update * * @param netName the net name * @param netVal the net val */ LogicUpdate(const std::string& netName, const LogicVal& netVal) : netName (&netName), netVal (netVal) {} LogicUpdate (): netName (NULL), netVal(LOGIC_UNKNOWN) {} friend bool operator == (const LogicUpdate& left, const LogicUpdate& right) { return ((*left.netName) == (*right.netName)) && (left.netVal == right.netVal); } friend bool operator != (const LogicUpdate& left, const LogicUpdate& right) { return !(left == right); } /** * string representation */ const std::string str() const { std::ostringstream ss; ss << "netName = " << *netName << " netVal = " << netVal; return ss.str (); } /** * Gets the net name. * * @return the net name */ const std::string& getNetName() const { return *netName; } /** * Gets the net val. * * @return the net val */ LogicVal getNetVal() const { return netVal; } }; } // namespace des #endif /* DES_LOGICUPDATE_H_ */
0
rapidsai_public_repos/code-share/maxflow/galois/apps/des
rapidsai_public_repos/code-share/maxflow/galois/apps/des/unordered/DESunordered.cpp
/** main function for DESunordered -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author M. Amber Hassaan <[email protected]> */ #include "DESunordered.h" int main (int argc, char* argv[]) { des_unord::DESunordered m; m.run (argc, argv); return 0; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps/des
rapidsai_public_repos/code-share/maxflow/galois/apps/des/unordered/DESunordered.h
/** DES unordered Galois version -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author M. Amber Hassaan <[email protected]> */ #ifndef _DES_UNORDERED_H_ #define _DES_UNORDERED_H_ #include "Galois/Galois.h" #include "Galois/Accumulator.h" #include "Galois/Atomic.h" #include "Galois/WorkList/WorkList.h" #include "Galois/Runtime/ll/gio.h" #include "DESunorderedBase.h" namespace des_unord { static const bool DEBUG = false; class DESunordered: public DESunorderedBase { typedef Galois::GAccumulator<size_t> Accumulator; typedef Galois::GReduceMax<size_t> ReduceMax; typedef Galois::GAtomicPadded<bool> AtomicBool; typedef std::vector<AtomicBool> VecAtomicBool; /** * contains the loop body, called * by @see for_each */ struct Process { Graph& graph; VecAtomicBool& onWLflags; Accumulator& numEvents; Accumulator& numIter; ReduceMax& maxPending; Process ( Graph& graph, VecAtomicBool& onWLflags, Accumulator& numEvents, Accumulator& numIter, ReduceMax& maxPending) : graph (graph), onWLflags (onWLflags), numEvents (numEvents), numIter (numIter), maxPending (maxPending) {} void lockNeighborhood (GNode& activeNode) { // acquire locks on neighborhood: one shot graph.getData (activeNode, Galois::MethodFlag::CHECK_CONFLICT); // for (Graph::edge_iterator i = graph.edge_begin (activeNode, Galois::CHECK_CONFLICT) // , ei = graph.edge_end (activeNode, Galois::CHECK_CONFLICT); i != ei; ++i) { // GNode dst = graph.getEdgeDst (i); // graph.getData (dst, Galois::CHECK_CONFLICT); // } } /** * * Called by @see Galois::Runtime::for_each during * every iteration * * @param activeNode: the current active element * @param lwl: the worklist type */ template <typename WL> void operator () (GNode& activeNode, WL& lwl) { lockNeighborhood (activeNode); SimObj_ty* srcObj = static_cast<SimObj_ty*> (graph.getData (activeNode, Galois::MethodFlag::NONE)); // should be past the fail-safe point by now if (DEBUG) { Galois::Runtime::LL::gDebug("processing : ", srcObj->str ().c_str ()); } maxPending.update (srcObj->numPendingEvents ()); size_t proc = srcObj->simulate(graph, activeNode); // number of events processed numEvents += proc; for (Graph::edge_iterator i = graph.edge_begin (activeNode, Galois::MethodFlag::NONE) , ei = graph.edge_end (activeNode, Galois::MethodFlag::NONE); i != ei; ++i) { const GNode dst = graph.getEdgeDst(i); SimObj_ty* dstObj = static_cast<SimObj_ty*> (graph.getData (dst, Galois::MethodFlag::NONE)); if (dstObj->isActive () && !bool (onWLflags [dstObj->getID ()]) && onWLflags[dstObj->getID ()].cas (false, true)) { if (DEBUG) { Galois::Runtime::LL::gDebug ("Added %d neighbor: ", bool (onWLflags[dstObj->getID ()]), dstObj->str ().c_str ()); } lwl.push (dst); } } if (srcObj->isActive()) { lwl.push (activeNode); if (DEBUG) { Galois::Runtime::LL::gDebug ("Added %d self: " , bool (onWLflags[srcObj->getID ()]), srcObj->str ().c_str ()); } } else { onWLflags[srcObj->getID ()] = false; if (DEBUG) { Galois::Runtime::LL::gDebug ("not adding %d self: ", bool (onWLflags[srcObj->getID ()]), srcObj->str ().c_str ()); } } numIter += 1; } }; /** * Run loop. * * Galois worklists, currently, do not support set semantics, therefore, duplicates can be present on the workset. * To ensure uniqueness of items on the worklist, we keep a list of boolean flags for each node, * which indicate whether the node is on the worklist. When adding a node to the worklist, the * flag corresponding to a node is set to True if it was previously False. The flag reset to False * when the node is removed from the worklist. This list of flags provides a cheap way of * implementing set semantics. * */ virtual void runLoop (const SimInit_ty& simInit, Graph& graph) { std::vector<GNode> initialActive; VecAtomicBool onWLflags; initWorkList (graph, initialActive, onWLflags); Accumulator numEvents; Accumulator numIter; ReduceMax maxPending; Process p(graph, onWLflags, numEvents, numIter, maxPending); typedef Galois::WorkList::dChunkedFIFO<CHUNK_SIZE, GNode> WL_ty; // typedef Galois::Runtime::WorkList::GFIFO<GNode> WL_ty; Galois::for_each(initialActive.begin (), initialActive.end (), p, Galois::wl<WL_ty>()); std::cout << "Number of events processed = " << numEvents.reduce () << std::endl; std::cout << "Number of iterations performed = " << numIter.reduce () << std::endl; std::cout << "Maximum size of pending events = " << maxPending.reduce() << std::endl; } void checkPostState (Graph& graph, VecAtomicBool& onWLflags) { for (Graph::iterator n = graph.begin (), endn = graph.end (); n != endn; ++n) { SimObj_ty* so = static_cast<SimObj_ty*> (graph.getData (*n, Galois::MethodFlag::NONE)); if (so->isActive ()) { std::cout << "ERROR: Found Active: " << so->str () << std::endl << "onWLflags = " << onWLflags[so->getID ()] << ", numPendingEvents = " << so->numPendingEvents () << std::endl; } } } virtual std::string getVersion () const { return "Unordered (Chandy-Misra) parallel"; } }; } // end namespace des_unord #endif // _DES_UNORDERED_H_
0
rapidsai_public_repos/code-share/maxflow/galois/apps/des
rapidsai_public_repos/code-share/maxflow/galois/apps/des/unordered/DESunorderedBase.h
/** DES unordered, common typedefs -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author M. Amber Hassaan <[email protected]> */ #include "SimInit.h" #include "abstractMain.h" #include "SimObject.h" namespace des_unord { namespace cll = llvm::cl; static cll::opt<unsigned> eventsPerIter("epi", cll::desc ("number of events processed per iteration (max.)"), cll::init (0)); struct TypeHelper { typedef des::Event<des::LogicUpdate> Event_ty; typedef Event_ty::BaseSimObj_ty BaseSimObj_ty; typedef des_unord::SimObject<Event_ty> SimObj_ty; typedef des::SimGate<SimObj_ty> SimGate_ty; typedef des::Input<SimObj_ty> Input_ty; typedef des::Output<SimObj_ty> Output_ty; typedef des::SimInit<SimGate_ty, Input_ty, Output_ty> SimInit_ty; }; class DESunorderedBase: public des::AbstractMain<des_unord::TypeHelper::SimInit_ty> , public des_unord::TypeHelper { protected: virtual void initRemaining (const SimInit_ty& simInit, Graph& graph) { SimObj_ty::NEVENTS_PER_ITER = eventsPerIter; if (SimObj_ty::NEVENTS_PER_ITER == 0) { SimObj_ty::NEVENTS_PER_ITER = DEFAULT_EPI; } // post the initial events on their stations for (std::vector<Event_ty>::const_iterator i = simInit.getInitEvents ().begin () , endi = simInit.getInitEvents ().end (); i != endi; ++i) { SimObj_ty* so = static_cast<SimObj_ty*> (i->getRecvObj ()); so->recv (*i); } } template <typename WL, typename B> void initWorkList (Graph& graph, WL& workList, std::vector<B>& onWLflags) { onWLflags.clear (); workList.clear (); onWLflags.resize (graph.size (), B (false)); // set onWLflags for input objects for (Graph::iterator n = graph.begin () , endn = graph.end (); n != endn; ++n) { SimObj_ty* so = static_cast<SimObj_ty*> (graph.getData (*n, Galois::MethodFlag::NONE)); if (so->isActive ()) { workList.push_back (*n); onWLflags[so->getID ()] = true; } } std::cout << "Initial workList size = " << workList.size () << std::endl; } }; } // end namespace des_unord
0
rapidsai_public_repos/code-share/maxflow/galois/apps/des
rapidsai_public_repos/code-share/maxflow/galois/apps/des/unordered/DESunorderedSerial.h
/** DES serial unordered version -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author M. Amber Hassaan <[email protected]> */ #ifndef _DES_UNORDERED_SERIAL_H_ #define _DES_UNORDERED_SERIAL_H_ #include <deque> #include <functional> #include <cassert> #include "DESunorderedBase.h" namespace des_unord { class DESunorderedSerial: public des_unord::DESunorderedBase { virtual std::string getVersion () const { return "Unordered (Chandy-Misra) serial"; } /** * Run loop. * Does not use Galois::Runtime or Galois worklists * * To ensure uniqueness of items on the workList, we keep a list of boolean flags for each node, * which indicate whether the node is on the workList. When adding a node to the workList, the * flag corresponding to a node is set to True if it was previously False. The flag reset to False * when the node is removed from the workList. This list of flags provides a cheap way of * implementing set semantics. * */ virtual void runLoop (const SimInit_ty& simInit, Graph& graph) { std::deque<GNode> workList; std::vector<bool> onWLflags; initWorkList (graph, workList, onWLflags); size_t maxPending = 0; size_t numEvents = 0; size_t numIter = 0; while (!workList.empty ()) { GNode activeNode = workList.front (); workList.pop_front (); SimObj_ty* srcObj = static_cast<SimObj_ty*> (graph.getData (activeNode, Galois::MethodFlag::NONE)); maxPending = std::max (maxPending, srcObj->numPendingEvents ()); numEvents += srcObj->simulate(graph, activeNode); for (Graph::edge_iterator i = graph.edge_begin (activeNode, Galois::MethodFlag::NONE) , ei = graph.edge_end (activeNode, Galois::MethodFlag::NONE); i != ei; ++i) { GNode dst = graph.getEdgeDst(i); SimObj_ty* dstObj = static_cast<SimObj_ty*> (graph.getData (dst, Galois::MethodFlag::NONE)); if (dstObj->isActive ()) { if (!onWLflags[dstObj->getID ()]) { // set the flag to indicate presence on the workList onWLflags[dstObj->getID ()] = true; workList.push_back (dst); } } } if (srcObj->isActive()) { workList.push_back (activeNode); } else { // reset the flag to indicate absence on the workList onWLflags[srcObj->getID ()] = false; } ++numIter; } std::cout << "Simulation ended" << std::endl; std::cout << "Number of events processed = " << numEvents << " Iterations = " << numIter << std::endl; std::cout << "Max size of pending events = " << maxPending << std::endl; } }; } // end namspace des_unord #endif // _DES_UNORDERED_SERIAL_H_
0
rapidsai_public_repos/code-share/maxflow/galois/apps/des
rapidsai_public_repos/code-share/maxflow/galois/apps/des/unordered/DESunorderedSerial.cpp
/** main function for DESunorderedSerial -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author M. Amber Hassaan <[email protected]> */ #include "DESunorderedSerial.h" int main (int argc, char* argv[]) { des_unord::DESunorderedSerial s; s.run (argc, argv); return 0; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps/des
rapidsai_public_repos/code-share/maxflow/galois/apps/des/unordered/SimObject.h
/** SimObject: the abstract interface to be implemented by any simulation object -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author M. Amber Hassaan <[email protected]> */ #ifndef SIMOBJECT_H_ #define SIMOBJECT_H_ #include <vector> #include <queue> #include <cassert> #include "comDefs.h" #include "BaseSimObject.h" #include "Event.h" #include "Galois/PriorityQueue.h" #include "Galois/Runtime/ll/gio.h" //TODO: modeling one output for now. Need to extend for multiple outputs /** * @section Description * * The Class SimObject represents an abstract simulation object (processing station). A simulation application * would inherit from this class. */ namespace des_unord { template <typename Event_tp> class SimObject: public des::BaseSimObject<Event_tp> { typedef typename des::BaseSimObject<Event_tp> Base; typedef Event_tp Event_ty; protected: struct SendWrapperImpl: public Base::SendWrapper { virtual void send (Base* rs, const Event_ty& e) { SimObject* recvObj = static_cast<SimObject*> (rs); recvObj->recv (e); } }; typedef des::EventRecvTimeLocalTieBrkCmp<Event_ty> Cmp; typedef typename Galois::ThreadSafeOrderedSet<Event_ty, Cmp> PQ; // typedef typename Galois::ThreadSafeMinHeap<Event_ty, Cmp> PQ; static const bool DEBUG = false; unsigned numOutputs; unsigned numInputs; std::vector<des::SimTime> inputTimes; PQ pendingEvents; public: static size_t NEVENTS_PER_ITER; SimObject (size_t id, unsigned numOutputs, unsigned numInputs) : Base (id), numOutputs (numOutputs), numInputs (numInputs) { assert (numOutputs == 1); inputTimes.resize (numInputs, 0); } virtual ~SimObject () {} void recv (const Event_ty& e) { size_t inIdx = this->getInputIndex (e); assert (inIdx < numInputs); // GALOIS_DEBUG ("%s, Received : %s\n", this->str ().c_str (), e.str ().c_str ()); if (inputTimes[inIdx] > e.getRecvTime () && e.getRecvTime () < des::INFINITY_SIM_TIME ) { Galois::Runtime::LL::gDebug ("Non-FIFO order on input[",inIdx,"], last msg time=",inputTimes[inIdx],", current message =", e.str ().c_str ()); assert (inputTimes[inIdx] <= e.getRecvTime ()); } // assert (inputTimes[inIdx] <= e.getRecvTime ()); inputTimes[inIdx] = e.getRecvTime (); pendingEvents.push (e); } /** * Simulate. * * @param graph: the graph composed of simulation objects/stations and communication links * @param myNode the node in the graph that has this SimObject as its node data * @return number of events that were processed during the call */ template <typename G> size_t simulate(G& graph, typename G::GraphNode& myNode) { assert (isActive ()); // if (!isActive ()) { return 0; } size_t nevents = 0; if (isActive ()) { des::SimTime clock = this->getClock (); while ((!pendingEvents.empty()) && (pendingEvents.top ().getRecvTime () <= clock) && (nevents < NEVENTS_PER_ITER)) { Event_ty event = pendingEvents.pop (); // GALOIS_DEBUG ("%s, Processing: %s\n", this->str ().c_str (), event.str ().c_str ()); //DEBUG if (DEBUG && !pendingEvents.empty ()) { Event_ty curr = event; Event_ty next = pendingEvents.top (); if (curr.getRecvTime () > next.getRecvTime ()) { std::cerr << "ERROR: curr > next" << std::endl; std::cerr << "curr = " << curr.str () << std::endl << "next = " << next.str () << std::endl; } } assert (graph.getData(myNode, Galois::MethodFlag::NONE) == this); // should already own a lock assert (event.getRecvObj () == this); typename Base::template OutDegIterator<G> beg = Base::make_begin (graph, myNode); typename Base::template OutDegIterator<G> end = Base::make_end (graph, myNode); SendWrapperImpl sendWrap; this->execEventIntern(event, sendWrap, beg, end); ++nevents; } } return nevents; } /** * Checks if is active. * i.e. can process some of its pending events * * * @return true, if is active */ bool isActive() const { // not active if pendingEvents is empty // not active if earliest pending event has a time stamp less than // the latest time on an input i.e. possibly waiting for an earlier // event on some input bool notActive = true; if (!pendingEvents.empty ()) { notActive = false; const des::SimTime& min_time = pendingEvents.top ().getRecvTime (); for (std::vector<des::SimTime>::const_iterator t = inputTimes.begin () , endt = inputTimes.end (); t != endt; ++t) { if ((*t < des::INFINITY_SIM_TIME) && (*t < min_time)) { // not active if waiting for an earlier message on an input // input considered dead if last message on the input had a time stamp // of INFINITY_SIM_TIME or greater notActive = true; break; } } } return !notActive; } size_t numPendingEvents () const { return pendingEvents.size (); } /** * string representation for printing */ virtual std::string str() const { std::ostringstream ss; ss << Base::str (); for (size_t i = 0; i < numInputs; ++i) { ss << ", inputTimes[" << i << "] = " << inputTimes[i]; } if (DEBUG) { for (size_t i = 0; i < numInputs; ++i) { ss << ", inputTimes[" << i << "] = " << inputTimes[i]; } ss << std::endl; ss << ", active = " << isActive () << ", pendingEvents.size() = " << pendingEvents.size () << ", pendingEvent.top () = " << pendingEvents.top ().str () << std::endl; } return ss.str (); } protected: /** * @return the min of the time stamps of the latest message recieved on each * input * An input becomes dead when a message with time INFINITY_SIM_TIME is received * on it, * such dead inputs are not included in clock computation */ des::SimTime getClock () const { assert (inputTimes.size () == numInputs); des::SimTime min_t = 2 * des::INFINITY_SIM_TIME; // to ensure a value of INFINITY_SIM_TIME + any small delay for (std::vector<des::SimTime>::const_iterator i = inputTimes.begin () , endi = inputTimes.end (); i != endi; ++i) { if (*i < des::INFINITY_SIM_TIME) { // min_t = std::min (*i, min_t); } } return min_t; // std::vector<des::SimTime>::const_iterator min_pos = std::min_element (inputTimes.begin (), inputTimes.end ()); // return *min_pos; } }; // end class } // end namespace des_unord template <typename Event_tp> size_t des_unord::SimObject<Event_tp>::NEVENTS_PER_ITER = 1; #endif /* SIMOBJECT_H_ */
0
rapidsai_public_repos/code-share/maxflow/galois/apps/des
rapidsai_public_repos/code-share/maxflow/galois/apps/des/common/SimInit.h
/** SimInit initializes the circuit graph and creates initial set of events -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * Created on: Jun 23, 2011 * * @author M. Amber Hassaan <[email protected]> */ #ifndef DES_SIMINIT_H #define DES_SIMINIT_H #include <vector> #include <map> #include <set> #include <string> #include <iostream> #include <cassert> #include "comDefs.h" #include "BaseSimObject.h" #include "Event.h" #include "SimInit.h" #include "SimGate.h" #include "Input.h" #include "Output.h" #include "logicDefs.h" #include "LogicUpdate.h" #include "LogicFunctions.h" #include "LogicGate.h" #include "OneInputGate.h" #include "TwoInputGate.h" #include "BasicPort.h" #include "NetlistParser.h" namespace des { template <typename SimGate_tp, typename Input_tp, typename Output_tp> class SimInit { public: typedef NetlistParser::StimulusMapType StimulusMapType; typedef SimGate_tp SimGate_ty; typedef Input_tp Input_ty; typedef Output_tp Output_ty; typedef Event<LogicUpdate> Event_ty; typedef BaseSimObject<Event_ty> BaseSimObj_ty; protected: /** The netlist parser. */ NetlistParser parser; /** The input simulation objs. */ std::vector<BaseSimObj_ty*> inputObjs; /** The output simulation objs. */ std::vector<BaseSimObj_ty*> outputObjs; /** The gates i.e. other than input and output ports. */ std::vector<BaseSimObj_ty*> gateObjs; /** The initial events. */ std::vector<Event_ty> initEvents; /** The num edges. */ size_t numEdges; /** The num nodes. */ size_t numNodes; /** Counter for BaseSimObj_ty's */ size_t simObjCntr; protected: /** * Creates the input simulation objs. */ void createInputObjs() { const std::vector<BasicPort*>& inputPorts = parser.getInputPorts (); for (std::vector<BasicPort*>::const_iterator i = inputPorts.begin (), e = inputPorts.end (); i != e; ++i) { inputObjs.push_back(new Input_ty((simObjCntr++), **i)); } } /** * Creates the output simulation objs. */ void createOutputObjs() { const std::vector<BasicPort*>& outputPorts = parser.getOutputPorts (); for (std::vector<BasicPort*>::const_iterator i = outputPorts.begin (), e = outputPorts.end (); i != e; ++i) { outputObjs.push_back(new Output_ty((simObjCntr++), **i)); } } /** * Creates the gate objs. */ void createGateObjs() { for (std::vector<LogicGate*>::const_iterator i = parser.getGates ().begin (), ei = parser.getGates ().end (); i != ei; ++i) { gateObjs.push_back (new SimGate_ty ((simObjCntr++), **i)); } } /** * Creates the initial events. */ void createInitEvents (bool createNullEvents=true) { const StimulusMapType& inputStimulusMap = parser.getInputStimulusMap(); for (std::vector<BaseSimObj_ty*>::const_iterator i = inputObjs.begin (), ei = inputObjs.end (); i != ei; ++i ) { Input_ty* currInput = dynamic_cast<Input_ty*> (*i); assert ((currInput != NULL)); const BasicPort& impl = currInput->getImpl (); StimulusMapType::const_iterator it = inputStimulusMap.find (impl.getOutputName ()); assert ((it != inputStimulusMap.end ())); const std::vector<std::pair<SimTime, LogicVal> >& tvList = it->second; for (std::vector< std::pair<SimTime, LogicVal> >::const_iterator j = tvList.begin () , ej = tvList.end (); j != ej; ++j) { const std::pair<SimTime, LogicVal>& p = *j; LogicUpdate lu(impl.getInputName(), p.second); Event_ty e = currInput->makeEvent(currInput, lu, Event_ty::REGULAR_EVENT, p.first); initEvents.push_back(e); } if (createNullEvents) { // final NULL_EVENT scheduled at INFINITY_SIM_TIME to signal that no more // non-null events will be received on an input LogicUpdate lu (impl.getInputName (), LOGIC_ZERO); Event_ty fe = currInput->makeEvent (currInput, lu, Event_ty::NULL_EVENT, INFINITY_SIM_TIME); initEvents.push_back (fe); } } } /** * helper function, which creates graph nodes corresponding to any simulation object * and add the node to the graph. No connections made yet */ template <typename G> static void createGraphNodes (const std::vector<BaseSimObj_ty*>& simObjs, G& graph, size_t& numNodes) { typedef typename G::GraphNode GNode; for (typename std::vector<BaseSimObj_ty*>::const_iterator i = simObjs.begin (), ei = simObjs.end (); i != ei; ++i) { BaseSimObj_ty* so = *i; GNode n = graph.createNode(so); graph.addNode(n, Galois::MethodFlag::NONE); ++numNodes; } } /** * Creates the connections i.e. edges in the graph * An edge is created whenever a gate's output is connected to * another gate's input. */ template <typename G> void createConnections (G& graph) { typedef typename G::GraphNode GNode; // read in all nodes first, since iterator may not support concurrent modification std::vector<GNode> allNodes; for (typename G::iterator i = graph.begin (), ei = graph.end (); i != ei; ++i) { allNodes.push_back (*i); } for (typename std::vector<GNode>::iterator i = allNodes.begin (), ei = allNodes.end (); i != ei; ++i) { GNode& src = *i; SimGate_tp* sg = dynamic_cast<SimGate_tp*> (graph.getData (src, Galois::MethodFlag::NONE)); assert (sg != NULL); const LogicGate& srcGate = sg->getImpl (); const std::string& srcOutName = srcGate.getOutputName (); for (typename std::vector<GNode>::iterator j = allNodes.begin (), ej = allNodes.end (); j != ej; ++j) { GNode& dst = *j; SimGate_tp* dg = dynamic_cast<SimGate_tp*> (graph.getData (dst, Galois::MethodFlag::NONE)); assert (dg != NULL); const LogicGate& dstGate = dg->getImpl (); if (dstGate.hasInputName (srcOutName)) { assert (&srcGate != &dstGate); // disallowing self loops if (graph.findEdge(src, dst) == graph.edge_end(src)) { ++numEdges; graph.addEdge (src, dst, Galois::MethodFlag::NONE); } } } // end inner for } // end outer for } /** * destructor helper */ void destroy () { destroyVec (inputObjs); destroyVec (outputObjs); destroyVec (gateObjs); initEvents.clear (); } public: /** * Instantiates a new simulation initializer. * * @param netlistFile the netlist file */ SimInit(const std::string& netlistFile) : parser(netlistFile), simObjCntr(0) {} virtual ~SimInit () { destroy (); } /** * Initialize. * * Processing steps * create the input and output objects and add to netlistArrays * create the gate objects * connect the netlists by populating the fanout lists * create a list of initial events */ template <typename G> void initialize (G& graph) { typedef typename G::GraphNode GNode; destroy (); numNodes = 0; numEdges = 0; // create input and output objects createInputObjs (); createOutputObjs (); createGateObjs (); createInitEvents (); // create nodes for inputObjs createGraphNodes (inputObjs, graph, numNodes); // create nodes for outputObjs createGraphNodes (outputObjs, graph, numNodes); // create nodes for all gates createGraphNodes (gateObjs, graph, numNodes); // create the connections based on net names createConnections(graph); } /** * Verify the output by comparing the final values of the outputs of the circuit * from simulation against the values precomputed in the netlist file */ void verify () const { // const std::vector<BaseSimObj_ty*>& outputObjs = getOutputObjs(); const std::map<std::string, LogicVal>& outValues = getOutValues(); int exitStatus = 0; for (typename std::vector<BaseSimObj_ty*>::const_iterator i = outputObjs.begin () , ei = outputObjs.end (); i != ei; ++i) { BaseSimObj_ty* so = *i; Output_ty* outObj = dynamic_cast< Output_ty* > (so); assert (outObj != NULL); BasicPort& outp = outObj->getImpl (); const LogicVal& simulated = outp.getOutputVal(); const LogicVal& expected = (outValues.find (outp.getInputName ()))->second; if (simulated != expected) { exitStatus = 1; std::cerr << "Wrong output value for " << outp.getInputName () << ", expected : " << expected << ", simulated : " << simulated << std::endl; } } if (exitStatus != 0) { std::cerr << "-----------------------------------------------------------" << std::endl; for (typename std::vector<BaseSimObj_ty*>::const_iterator i = outputObjs.begin () , ei = outputObjs.end (); i != ei; ++i) { BaseSimObj_ty* so = *i; Output_ty* outObj = dynamic_cast< Output_ty* > (so); assert (outObj != NULL); BasicPort& outp = outObj->getImpl (); const LogicVal& expected = (outValues.find (outp.getInputName ()))->second; std::cerr << "expected: " << expected << ", " << outObj->str () << std::endl; } abort (); } else { std::cout << ">>> OK: Simulation verified as correct" << std::endl; } } /** * Gets the inits the events. * * @return the inits the events */ const std::vector<Event_ty>& getInitEvents() const { return initEvents; } /** * Gets the input names. * * @return the input names */ const std::vector<std::string>& getInputNames() const { return parser.getInputNames(); } /** * Gets the input objs. * * @return the input objs */ const std::vector<BaseSimObj_ty*>& getInputObjs() const { return inputObjs; } /** * Gets the output names. * * @return the output names */ const std::vector<std::string>& getOutputNames() const { return parser.getOutputNames(); } /** * Gets the output objs. * * @return the output objs */ const std::vector<BaseSimObj_ty*> getOutputObjs() const { return outputObjs; } /** * Gets the out values. * * @return the out values */ const std::map<std::string, LogicVal>& getOutValues() const { return parser.getOutValues(); } /** * Gets the number edges. * * @return the number edges */ size_t getNumEdges() const { return numEdges; } /** * Gets the number of nodes * * @return the number of nodes */ size_t getNumNodes() const { return numNodes; } }; } // end namespace des #endif /* DES_SIMINIT_H */
0
rapidsai_public_repos/code-share/maxflow/galois/apps/des
rapidsai_public_repos/code-share/maxflow/galois/apps/des/common/Output.h
/** Output is an output port in the circuit -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author M. Amber Hassaan <[email protected]> */ #ifndef DES_OUTPUT_H_ #define DES_OUTPUT_H_ #include <iostream> #include <string> #include <cassert> #include "Input.h" namespace des { /** * The Class Output. */ template <typename S> class Output: public Input<S> { typedef Input<S> Base; typedef typename Base::Event_ty Event_ty; public: /** * Instantiates a new Output. */ Output(size_t id, des::BasicPort& impl) : Input<S> (id, impl) {} virtual Output* clone () const { return new Output (*this); } /** * A string representation */ virtual std::string str () const { std::ostringstream ss; ss << "Output: " << Base::Base::str (); return ss.str (); } protected: /** * Output just receives events and updates its state, does not send out any events */ virtual void execEventIntern (const Event_ty& event, typename Base::SendWrapper& sendWrap, typename Base::BaseOutDegIter& b, typename Base::BaseOutDegIter& e) { if (event.getType () != Event_ty::NULL_EVENT) { const des::LogicUpdate& lu = event.getAction (); if (lu.getNetName () == Base::getImpl ().getInputName ()) { Base::getImpl ().applyUpdate (lu); } else { Base::getImpl ().netNameMismatch (lu); } } } }; } // end namespace des #endif /* DES_OUTPUT_H_ */
0
rapidsai_public_repos/code-share/maxflow/galois/apps/des
rapidsai_public_repos/code-share/maxflow/galois/apps/des/common/Input.h
/** Input represents an input port in the circuit -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author M. Amber Hassaan <[email protected]> */ #ifndef DES_INPUT_H_ #define DES_INPUT_H_ #include <string> #include <cassert> #include "SimGate.h" #include "BasicPort.h" namespace des { template <typename S> class Input: public SimGate<S> { protected: typedef SimGate<S> Base; typedef typename Base::Event_ty Event_ty; public: /** * Instantiates a new Input. */ Input(size_t id, des::BasicPort& impl) : Base (id, impl) {} virtual Input* clone () const { return new Input (*this); } virtual des::BasicPort& getImpl () const { assert (dynamic_cast<des::BasicPort*> (&Base::getImpl ()) != NULL); des::BasicPort* ptr = static_cast<des::BasicPort*> (&Base::getImpl ()); assert (ptr != NULL); return *ptr; } /** * A string representation */ virtual std::string str () const { std::ostringstream ss; ss << "Input: " << Base::str (); return ss.str (); } protected: /** * Sends a copy of event at the input to all the outputs in the circuit * @see OneInputGate::execEvent(). * * @param event the event * @param sendWrap * @param b begining of range * @param e end of range */ virtual void execEventIntern (const Event_ty& event, typename Base::SendWrapper& sendWrap, typename Base::BaseOutDegIter& b, typename Base::BaseOutDegIter& e) { if (event.getType () == Event_ty::NULL_EVENT) { Base::execEventIntern (event, sendWrap, b, e); } else { const des::LogicUpdate& lu = event.getAction (); if (getImpl().getInputName () == lu.getNetName()) { getImpl().setInputVal (lu.getNetVal()); getImpl().setOutputVal (lu.getNetVal()); des::LogicUpdate drvFanout (getImpl ().getOutputName (), getImpl ().getOutputVal ()); Base::sendEventsToFanout (event, drvFanout, Event_ty::REGULAR_EVENT, sendWrap, b, e); } else { getImpl ().netNameMismatch (lu); } } } }; } // end namespace des #endif /* DES_INPUT_H_ */
0
rapidsai_public_repos/code-share/maxflow/galois/apps/des
rapidsai_public_repos/code-share/maxflow/galois/apps/des/common/SimGate.h
/** defines the interface for a SimGate and implements some common functionality -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * Created on: Jun 22, 2011 * * @author M. Amber Hassaan <[email protected]> */ #ifndef DES_SIMGATE_H #define DES_SIMGATE_H #include <string> #include <iostream> #include <cstdlib> #include <cassert> #include "logicDefs.h" #include "LogicUpdate.h" #include "LogicGate.h" #include "Event.h" #include "SimObject.h" namespace des { /** * The Class SimGate represents an abstract logic gate. */ template <typename S> class SimGate: public S { protected: typedef S Base; des::LogicGate& impl; public: typedef Event<LogicUpdate> Event_ty; SimGate (size_t id, des::LogicGate& impl) : Base (id, impl.getNumOutputs (), impl.getNumInputs ()), impl(impl) {} SimGate (const SimGate& that): Base (that), impl (that.impl) {} virtual SimGate* clone () const { return new SimGate (*this); } virtual des::LogicGate& getImpl () const { return impl; } virtual size_t getInputIndex (const Event_ty& event) const { assert (dynamic_cast<SimGate*> (event.getRecvObj ()) == this); const std::string& netName = event.getAction ().getNetName (); return impl.getInputIndex (netName); } /** * A string representation */ virtual std::string str () const { std::ostringstream ss; ss << Base::str () << ": " << impl.str (); return ss.str (); } protected: /** * Send events to fanout, which are the out going neighbors in the circuit graph. */ void sendEventsToFanout (const Event_ty& inputEvent, const des::LogicUpdate& msg, const Event_ty::Type& type, typename Base::SendWrapper& sendWrap, typename Base::BaseOutDegIter& b, typename Base::BaseOutDegIter& e) { assert (dynamic_cast<SimGate*> (this) != NULL); SimGate* srcGate = static_cast<SimGate*> (this); const des::SimTime& sendTime = inputEvent.getRecvTime(); for (; b != e; ++b) { assert (dynamic_cast<SimGate*> (*b) != NULL); SimGate* dstGate = static_cast<SimGate*> (*b); Event_ty ne = srcGate->makeEvent (dstGate, msg, type, sendTime, impl.getDelay ()); sendWrap.send (dstGate, ne); } } virtual void execEventIntern (const Event_ty& event, typename Base::SendWrapper& sendWrap, typename Base::BaseOutDegIter& b, typename Base::BaseOutDegIter& e) { if (event.getType () != Event_ty::NULL_EVENT) { // update the inputs of fanout gates const des::LogicUpdate& lu = event.getAction (); impl.applyUpdate (lu); } // else output is unchanged in case of NULL_EVENT des::LogicUpdate drvFanout (impl.getOutputName (), impl.getOutputVal ()); sendEventsToFanout (event, drvFanout, event.getType (), sendWrap, b, e); } }; } // end namespace des #endif // DES_SIMGATE_H
0
rapidsai_public_repos/code-share/maxflow/galois/apps/des
rapidsai_public_repos/code-share/maxflow/galois/apps/des/common/comDefs.h
/** Some common definitions and helper functions -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author M. Amber Hassaan <[email protected]> */ #ifndef DES_COM_DEFS_H #define DES_COM_DEFS_H #include <limits> #include <string> #include <algorithm> #include <vector> namespace des { /** * type for time in simulation world */ typedef long long SimTime; // const SimTime INFINITY_SIM_TIME = std::numeric_limits<SimTime>::max (); // The above definition is bad because INFINITY_SIM_TIME + small_value will cause an overflow // and the result is not INFINITY_SIM_TIME any more /** The Constant INFINITY_SIM_TIME is used by NULL_EVENT messages to signal the end of simulation. */ const SimTime INFINITY_SIM_TIME = (1 << 30); const SimTime MIN_DELAY = 1l; /** * Helper function to convert a string to lower case */ std::string toLowerCase (std::string str); /** * freeing pointers in a vector * before the vector itself is destroyed */ template <typename T> void destroyVec (std::vector<T*>& vec) { for (typename std::vector<T*>::iterator i = vec.begin (), ei = vec.end (); i != ei; ++i) { delete *i; *i = NULL; } vec.clear (); } } // namespace des #endif
0
rapidsai_public_repos/code-share/maxflow/galois/apps/des
rapidsai_public_repos/code-share/maxflow/galois/apps/des/common/comDefs.cpp
/** Implementation corresponding to @file comDefs.h -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author M. Amber Hassaan <[email protected]> */ #include "comDefs.h" std::string des::toLowerCase (std::string str) { std::transform (str.begin (), str.end (), str.begin (), ::tolower); return str; }
0
rapidsai_public_repos/code-share/maxflow/galois/apps/des
rapidsai_public_repos/code-share/maxflow/galois/apps/des/common/Event.h
/** Event: is the basic structure of an event in the simulation -*- C++ -*- * @file * @section License * * Galois, a framework to exploit amorphous data-parallelism in irregular * programs. * * Copyright (C) 2011, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. * * @author M. Amber Hassaan <[email protected]> */ #ifndef DES_EVENT_H #define DES_EVENT_H #include <string> #include <sstream> #include "comDefs.h" #include "BaseSimObject.h" /** * The Class Event. * * @param <A> the type representing the action to be performed on receipt of this event */ namespace des { template <typename A> class Event { // template <typename E> friend class des::BaseSimObject<Event>; public: enum Type { REGULAR_EVENT, NULL_EVENT }; typedef A Action_ty; typedef BaseSimObject<Event> BaseSimObj_ty; private: /** The id: not guaranteed to be unique. */ size_t id; /** The send obj. */ BaseSimObj_ty* sendObj; /** The recv obj. */ BaseSimObj_ty* recvObj; /** The action to be performed on receipt of this event. */ A action; /** type of event null or non-null */ Type type; /** The send time. */ SimTime sendTime; /** The recv time. */ SimTime recvTime; protected: /** * Instantiates a new base event. * * @param id not guaranteed to be unique * @param sendObj the sending simulation obj * @param recvObj the receiving simulatio obj * @param action the action * @param type the type * @param sendTime the send time * @param recvTime the recv time */ Event (size_t id, BaseSimObj_ty* sendObj, BaseSimObj_ty* recvObj, const A& action, const Type& type, const SimTime& sendTime, const SimTime& recvTime): id (id), sendObj (sendObj), recvObj (recvObj), action (action), type (type), sendTime (sendTime), recvTime (recvTime) {} public: friend bool operator == (const Event& left, const Event& right) { return (left.id == right.id) && (left.sendObj == right.sendObj) && (left.recvObj == right.recvObj) && (left.action == right.action) && (left.type == right.type) && (left.sendTime == right.sendTime) && (left.recvTime == right.recvTime); } friend bool operator != (const Event& left, const Event& right) { return !(left == right); } friend std::ostream& operator << (std::ostream& out, const Event& event) { return (out << event.str ()); } /** * Detailed string. * * @return the string */ std::string detailStr() const { std::ostringstream ss; ss << "Event-" << id << ", " << (type == NULL_EVENT ? "NULL_EVENT" : "REGULAR_EVENT") << ", sendTime = " << sendTime << ", recvTime = " << recvTime << ", sendObj = " << sendObj->getID () << ", recvObj = " << recvObj->getID () << std::endl; // << "action = " << action.str () << std::endl << std::endl; return ss.str (); } /** * a simpler string representation for debugging */ std::string shortStr () const { std::ostringstream ss; ss << getRecvTime (); return ss.str (); } inline std::string str () const { return detailStr (); } /** * Gets the send obj. * * @return the send obj */ BaseSimObj_ty* getSendObj() const { return sendObj; } /** * Gets the recv obj. * * @return the recv obj */ BaseSimObj_ty* getRecvObj() const { return recvObj; } /** * Gets the send time. * * @return the send time */ const SimTime& getSendTime() const { return sendTime; } /** * Gets the recv time. * * @return the recv time */ const SimTime& getRecvTime() const { return recvTime; } /** * Gets the action. * * @return the action */ const A& getAction() const { return action; } const Type& getType () const { return type; } /** * Gets the id. * * @return the id */ size_t getID() const { return id; } }; /** * EventRecvTimeLocalTieBrkCmp is used to compare two events and * break ties when the receiving time of two events is the same * * Ties between events with same recvTime need to be borken consistently, * i.e. compare(m,n) and compare (n,m) are consistent with each other during * the life of events 'm' and 'n'. * * There are at least two reasons for breaking ties between events of same time stamps: * * - Chandy-Misra's algorithm requires FIFO communication channels on edges between the * stations. i.e. On a given input edge, two events with the same time stamp should not be * reordered. Therefore ties must be resolved for events received on the same input i.e. when * the sender is the same for two events. * * - PriorityQueue's are usually implemented using heaps and trees, which rebalance when an item is * removed/added. This means if we add two items 'a' and 'b' with the same priority in the time * order (a,b), then depending on what other itmes are added and removed, we may end up removing 'a' and * 'b' in the order (b,a), i.e. PriorityQueue may reorder elements of same priority. Therefor, * If we break ties between events on same input and not break ties between events * on different inputs, this may result in reordering events on the same input. * */ template <typename Event_tp> struct EventRecvTimeLocalTieBrkCmp { /** * * Compares two events 'left' and 'right' based on getRecvTime(). * if recvTime is same, then we compare the sender (using id), because two events from the same * sender should not be reordered. * If the sender is the same then we use the id on the event to * break the tie, since, sender is guaranteed to assign a unique * id to events * * * @param left * @param right * @return -1 if left < right. 1 if left > right. Should not return 0 unless left and right are * aliases */ static int compare (const Event_tp& left, const Event_tp& right) { int res; if ( left.getRecvTime () < right.getRecvTime ()) { res = -1; } else if (left.getRecvTime () > right.getRecvTime ()) { res = 1; } else { res = left.getSendObj ()->getID () - right.getSendObj ()->getID (); if (res == 0) { // same sender res = left.getID () - right.getID (); } } return res; } bool operator () (const Event_tp& left, const Event_tp& right) const { return compare (left, right) < 0; } /** * returns true if left > right * Since std::priority_queue is a max heap, we use > semantics instead of < * in order to get a min heap and thus process events in increasing order of recvTime. */ struct RevCmp { bool operator () (const Event_tp& left, const Event_tp& right) const { return EventRecvTimeLocalTieBrkCmp::compare (left, right) > 0; } }; }; } // namespace des #endif // DES_EVENT_H
0