Run the MemorySanitizer pass after optimizations

The original MemorySanitizer paper [0] states that "For performance
reasons, MemorySanitizer runs near the end of the optimizer chain."

Running the optimizations first has the double advantage that their
workload does not increase by having to handle instrumented code, while
the MemorySanitizer pass also has less work when it only needs to instrument optimized code.

[0] https://research.google.com/pubs/archive/43308.pdf

Bug: b/173257647
Bug: b/188205704
Bug: chromium:1313907
Change-Id: Ib987688e25b558679de457ad7ff35d9f3c042e11
Reviewed-on: https://swiftshader-review.googlesource.com/c/SwiftShader/+/65430
Kokoro-Result: kokoro <noreply+kokoro@google.com>
Reviewed-by: Alexis Hétu <sugoi@google.com>
Tested-by: Nicolas Capens <nicolascapens@google.com>
diff --git a/src/Reactor/LLVMJIT.cpp b/src/Reactor/LLVMJIT.cpp
index 012e2f1..6fe0ff2 100644
--- a/src/Reactor/LLVMJIT.cpp
+++ b/src/Reactor/LLVMJIT.cpp
@@ -899,13 +899,6 @@
 		pm = pb.buildO0DefaultPipeline(llvm::OptimizationLevel::O0);
 	}
 
-	if(__has_feature(memory_sanitizer) && msanInstrumentation)
-	{
-		llvm::MemorySanitizerOptions msanOpts(0 /* TrackOrigins */, false /* Recover */, false /* Kernel */, true /* EagerChecks */);
-		pm.addPass(llvm::ModuleMemorySanitizerPass(msanOpts));
-		pm.addPass(llvm::createModuleToFunctionPassAdaptor(llvm::MemorySanitizerPass(msanOpts)));
-	}
-
 	if(optimizationLevel > 0)
 	{
 		fpm.addPass(llvm::SROAPass());
@@ -917,6 +910,13 @@
 		pm.addPass(llvm::createModuleToFunctionPassAdaptor(std::move(fpm)));
 	}
 
+	if(__has_feature(memory_sanitizer) && msanInstrumentation)
+	{
+		llvm::MemorySanitizerOptions msanOpts(0 /* TrackOrigins */, false /* Recover */, false /* Kernel */, true /* EagerChecks */);
+		pm.addPass(llvm::ModuleMemorySanitizerPass(msanOpts));
+		pm.addPass(llvm::createModuleToFunctionPassAdaptor(llvm::MemorySanitizerPass(msanOpts)));
+	}
+
 	pm.run(*module, mam);
 #else  // Legacy pass manager
 	llvm::legacy::PassManager passManager;
@@ -931,17 +931,17 @@
 		passManager.add(llvm::createCoroCleanupLegacyPass());
 	}
 
-	if(__has_feature(memory_sanitizer) && msanInstrumentation)
-	{
-		passManager.add(llvm::createMemorySanitizerLegacyPassPass());
-	}
-
 	if(optimizationLevel > 0)
 	{
 		passManager.add(llvm::createSROAPass());
 		passManager.add(llvm::createInstructionCombiningPass());
 	}
 
+	if(__has_feature(memory_sanitizer) && msanInstrumentation)
+	{
+		passManager.add(llvm::createMemorySanitizerLegacyPassPass());
+	}
+
 	passManager.run(*module);
 #endif
 }