From 953c4af0da7cc89d5432353bba6b5d951ed852b4 Mon Sep 17 00:00:00 2001
From: Prakalp Srivastava <psrivas2@illinois.edu>
Date: Wed, 5 Nov 2014 01:43:40 +0000
Subject: [PATCH] (1) Addrspace issue of NVPTX backend handled by swapping the
 enum values of Global and Generic memory in NVPTX backend. Still commiting
 the code with functions to change address space of arguments, but not calling
 them. Might need in future if things break.

---
 .../DFG2LLVM_NVPTX/DFG2LLVM_NVPTX.cpp         | 36 +++++++++++++++++--
 1 file changed, 34 insertions(+), 2 deletions(-)

diff --git a/llvm/lib/Transforms/DFG2LLVM_NVPTX/DFG2LLVM_NVPTX.cpp b/llvm/lib/Transforms/DFG2LLVM_NVPTX/DFG2LLVM_NVPTX.cpp
index cb6a2967bb..1526989e82 100644
--- a/llvm/lib/Transforms/DFG2LLVM_NVPTX/DFG2LLVM_NVPTX.cpp
+++ b/llvm/lib/Transforms/DFG2LLVM_NVPTX/DFG2LLVM_NVPTX.cpp
@@ -90,6 +90,7 @@ namespace {
 
     //Functions
     std::string getKernelsModuleName(Module &M);
+    void fixValueAddrspace(Value* V, unsigned addrspace);
     void changeArgAddrspace(Function* F, unsigned i);
     void addCLMetadata(Function* F);
     void writeKernelsModule();
@@ -841,7 +842,6 @@ namespace {
          re = IItoRemove.rend(); ri != re; ++ri)
       (*ri)->eraseFromParent();
 
-    changeArgAddrspace(F_nvptx, 1);
     addCLMetadata(F_nvptx);
     DEBUG(errs() << KernelM);
 
@@ -874,7 +874,39 @@ namespace {
     return mid.append("_kernels.ll");
   }
 
-  void CodeGenTraversal::changeArgAddrspace(Function* F, unsigned i) {
+  void CodeGenTraversal::fixValueAddrspace(Value* V, unsigned addrspace) {
+    assert(isa<PointerType>(V->getType())
+        && "Value should be of Pointer Type!");
+    PointerType* OldTy = cast<PointerType>(V->getType());
+    PointerType* NewTy = PointerType::get(OldTy->getElementType(), addrspace);
+    V->mutateType(NewTy);
+    for(Value::use_iterator ui = V->use_begin(), ue = V->use_end(); ui != ue; ui++) {
+      // Change all uses producing pointer type in same address space to new
+      // addressspace.
+      if(PointerType* PTy = dyn_cast<PointerType>(ui->getType())) {
+        if(PTy->getAddressSpace() == OldTy->getAddressSpace()) {
+          fixValueAddrspace(*ui, addrspace);
+        }
+      }
+    }
+  }
+
+  void CodeGenTraversal::changeArgAddrspace(Function* F, unsigned addrspace) {
+    std::vector<Type*> ArgTypes;
+    for(auto& arg: F->getArgumentList()) {
+      DEBUG(errs() << arg << "\n");
+      if(PointerType* argTy = dyn_cast<PointerType>(arg.getType())) {
+        if(argTy->getAddressSpace() == 0) {
+          fixValueAddrspace(&arg, addrspace);
+        }
+      }
+      ArgTypes.push_back(arg.getType());
+    }
+    FunctionType* FTy = FunctionType::get(F->getReturnType(), ArgTypes, false);
+    PointerType* PTy = FTy->getPointerTo(cast<PointerType>(F->getType())->getAddressSpace());
+
+    F->mutateType(PTy);
+    DEBUG(errs() << *F->getFunctionType() << "\n" <<*F << "\n");
   }
 
   void CodeGenTraversal::addCLMetadata(Function* F) {
-- 
GitLab