diff --git a/lib/Basic/SourceManager.cpp b/lib/Basic/SourceManager.cpp
index 96a526ad141d6bea2ab8976193957d1b599bd3f1..a540f3b9450fafbc3579b2540748e6ef399dd42b 100644
--- a/lib/Basic/SourceManager.cpp
+++ b/lib/Basic/SourceManager.cpp
@@ -732,6 +732,10 @@ FileID SourceManager::getFileIDLocal(unsigned SLocOffset) const {
 FileID SourceManager::getFileIDLoaded(unsigned SLocOffset) const {
   assert(SLocOffset >= CurrentLoadedOffset && "Bad function choice");
 
+  // Sanity checking, otherwise a bug may lead to hanging in release build.
+  if (SLocOffset < CurrentLoadedOffset)
+    return FileID();
+
   // Essentially the same as the local case, but the loaded array is sorted
   // in the other direction.