]> git.proxmox.com Git - mirror_edk2.git/blobdiff - BaseTools/Source/Python/AutoGen/AutoGen.py
BaseTools: Structure Pcd value override incorrect.
[mirror_edk2.git] / BaseTools / Source / Python / AutoGen / AutoGen.py
index ed0be3bc74f925bfa9072ddf3a52d2b96586d7c0..ac3cf7eef3e02d0dc0bfb0061c7579959ca0fb20 100644 (file)
 \r
 ## Import Modules\r
 #\r
+from __future__ import print_function\r
+from __future__ import absolute_import\r
 import Common.LongFilePathOs as os\r
 import re\r
 import os.path as path\r
 import copy\r
 import uuid\r
 \r
-import GenC\r
-import GenMake\r
-import GenDepex\r
-from StringIO import StringIO\r
+from . import GenC\r
+from . import GenMake\r
+from . import GenDepex\r
+from io import BytesIO\r
 \r
-from StrGather import *\r
-from BuildEngine import BuildRule\r
+from .StrGather import *\r
+from .BuildEngine import BuildRule\r
 \r
 from Common.LongFilePathSupport import CopyLongFilePath\r
 from Common.BuildToolError import *\r
@@ -37,21 +39,22 @@ from Common.StringUtils import *
 import Common.GlobalData as GlobalData\r
 from GenFds.FdfParser import *\r
 from CommonDataClass.CommonClass import SkuInfoClass\r
-from Workspace.BuildClassObject import *\r
 from GenPatchPcdTable.GenPatchPcdTable import parsePcdInfoFromMapFile\r
 import Common.VpdInfoFile as VpdInfoFile\r
-from GenPcdDb import CreatePcdDatabaseCode\r
+from .GenPcdDb import CreatePcdDatabaseCode\r
 from Workspace.MetaFileCommentParser import UsageList\r
 from Workspace.WorkspaceCommon import GetModuleLibInstances\r
 from Common.MultipleWorkspace import MultipleWorkspace as mws\r
-import InfSectionParser\r
+from . import InfSectionParser\r
 import datetime\r
 import hashlib\r
-from GenVar import VariableMgr,var_info\r
+from .GenVar import VariableMgr, var_info\r
 from collections import OrderedDict\r
 from collections import defaultdict\r
 from Workspace.WorkspaceCommon import OrderedListDict\r
 \r
+from Common.caching import cached_property, cached_class_function\r
+\r
 ## Regular expression for splitting Dependency Expression string into tokens\r
 gDepexTokenPattern = re.compile("(\(|\)|\w+| \S+\.inf)")\r
 \r
@@ -76,7 +79,7 @@ gEfiVarStoreNamePattern = re.compile("\s*name\s*=\s*(\w+)")
 gEfiVarStoreGuidPattern = re.compile("\s*guid\s*=\s*({.*?{.*?}\s*})")\r
 \r
 ## Mapping Makefile type\r
-gMakeTypeMap = {"MSFT":"nmake", "GCC":"gmake"}\r
+gMakeTypeMap = {TAB_COMPILER_MSFT:"nmake", "GCC":"gmake"}\r
 \r
 \r
 ## Build rule configuration file\r
@@ -193,13 +196,12 @@ class AutoGen(object):
     def __new__(cls, Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs):\r
         # check if the object has been created\r
         Key = (Target, Toolchain, Arch, MetaFile)\r
-        try:\r
+        if Key in cls.__ObjectCache:\r
             # if it exists, just return it directly\r
             return cls.__ObjectCache[Key]\r
-        except:\r
             # it didnt exist. create it, cache it, then return it\r
-            cls.__ObjectCache[Key] = super(AutoGen, cls).__new__(cls)\r
-            return cls.__ObjectCache[Key]\r
+        RetVal = cls.__ObjectCache[Key] = super(AutoGen, cls).__new__(cls)\r
+        return RetVal\r
 \r
     def __init__ (self, Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs):\r
         super(AutoGen, self).__init__(self, Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs)\r
@@ -234,13 +236,11 @@ class AutoGen(object):
 class WorkspaceAutoGen(AutoGen):\r
     # call super().__init__ then call the worker function with different parameter count\r
     def __init__(self, Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs):\r
-        try:\r
-            self._Init\r
-        except:\r
+        if not hasattr(self, "_Init"):\r
             super(WorkspaceAutoGen, self).__init__(Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs)\r
             self._InitWorker(Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs)\r
             self._Init = True\r
-    \r
+\r
     ## Initialize WorkspaceAutoGen\r
     #\r
     #   @param  WorkspaceDir            Root directory of workspace\r
@@ -309,7 +309,7 @@ class WorkspaceAutoGen(AutoGen):
                             ExtraData="Build target [%s] is not supported by the platform. [Valid target: %s]"\r
                                       % (self.BuildTarget, " ".join(self.Platform.BuildTargets)))\r
 \r
-        \r
+\r
         # parse FDF file to get PCDs in it, if any\r
         if not self.FdfFile:\r
             self.FdfFile = self.Platform.FlashDefinition\r
@@ -440,7 +440,7 @@ class WorkspaceAutoGen(AutoGen):
                                     MGen = ModuleAutoGen(self, BuildData.MetaFile, Target, Toolchain, Arch, self.MetaFile)\r
                                     if MGen and MGen.IsLibrary:\r
                                         if MGen in PGen.LibraryAutoGenList:\r
-                                            ReferenceModules = MGen._ReferenceModules\r
+                                            ReferenceModules = MGen.ReferenceModules\r
                                             for ReferenceModule in ReferenceModules:\r
                                                 if ReferenceModule.MetaFile in Platform.Modules:\r
                                                     RefPlatformModule = Platform.Modules[str(ReferenceModule.MetaFile)]\r
@@ -567,7 +567,7 @@ class WorkspaceAutoGen(AutoGen):
                     DecPcdsKey.add((Pcd[0], Pcd[1], Pcd[2]))\r
 \r
             Platform.SkuName = self.SkuId\r
-            for Name, Guid in PcdSet:\r
+            for Name, Guid,Fileds in PcdSet:\r
                 if (Name, Guid) not in DecPcds:\r
                     EdkLogger.error(\r
                         'build',\r
@@ -581,7 +581,6 @@ class WorkspaceAutoGen(AutoGen):
                     if (Name, Guid, TAB_PCDS_FIXED_AT_BUILD) in DecPcdsKey \\r
                         or (Name, Guid, TAB_PCDS_PATCHABLE_IN_MODULE) in DecPcdsKey \\r
                         or (Name, Guid, TAB_PCDS_FEATURE_FLAG) in DecPcdsKey:\r
-                        Platform.AddPcd(Name, Guid, PcdSet[Name, Guid])\r
                         continue\r
                     elif (Name, Guid, TAB_PCDS_DYNAMIC) in DecPcdsKey or (Name, Guid, TAB_PCDS_DYNAMIC_EX) in DecPcdsKey:\r
                         EdkLogger.error(\r
@@ -618,9 +617,6 @@ class WorkspaceAutoGen(AutoGen):
         #\r
         self._CheckPcdDefineAndType()\r
 \r
-#         if self.FdfFile:\r
-#             self._CheckDuplicateInFV(Fdf)\r
-\r
         #\r
         # Create BuildOptions Macro & PCD metafile, also add the Active Platform and FDF file.\r
         #\r
@@ -688,7 +684,7 @@ class WorkspaceAutoGen(AutoGen):
             os.makedirs(self.BuildDir)\r
         with open(os.path.join(self.BuildDir, 'AutoGen'), 'w+') as file:\r
             for f in AllWorkSpaceMetaFiles:\r
-                print >> file, f\r
+                print(f, file=file)\r
         return True\r
 \r
     def _GenPkgLevelHash(self, Pkg):\r
@@ -760,131 +756,6 @@ class WorkspaceAutoGen(AutoGen):
 \r
         return AllWorkSpaceMetaFiles\r
 \r
-    ## _CheckDuplicateInFV() method\r
-    #\r
-    # Check whether there is duplicate modules/files exist in FV section. \r
-    # The check base on the file GUID;\r
-    #\r
-    def _CheckDuplicateInFV(self, Fdf):\r
-        for Fv in Fdf.Profile.FvDict:\r
-            _GuidDict = {}\r
-            for FfsFile in Fdf.Profile.FvDict[Fv].FfsList:\r
-                if FfsFile.InfFileName and FfsFile.NameGuid is None:\r
-                    #\r
-                    # Get INF file GUID\r
-                    #\r
-                    InfFoundFlag = False\r
-                    for Pa in self.AutoGenObjectList:\r
-                        if InfFoundFlag:\r
-                            break\r
-                        for Module in Pa.ModuleAutoGenList:\r
-                            if path.normpath(Module.MetaFile.File) == path.normpath(FfsFile.InfFileName):\r
-                                InfFoundFlag = True\r
-                                if Module.Guid.upper() not in _GuidDict:\r
-                                    _GuidDict[Module.Guid.upper()] = FfsFile\r
-                                    break\r
-                                else:\r
-                                    EdkLogger.error("build",\r
-                                                    FORMAT_INVALID,\r
-                                                    "Duplicate GUID found for these lines: Line %d: %s and Line %d: %s. GUID: %s" % (FfsFile.CurrentLineNum,\r
-                                                                                                                                   FfsFile.CurrentLineContent,\r
-                                                                                                                                   _GuidDict[Module.Guid.upper()].CurrentLineNum,\r
-                                                                                                                                   _GuidDict[Module.Guid.upper()].CurrentLineContent,\r
-                                                                                                                                   Module.Guid.upper()),\r
-                                                    ExtraData=self.FdfFile)\r
-                    #\r
-                    # Some INF files not have entity in DSC file. \r
-                    #\r
-                    if not InfFoundFlag:\r
-                        if FfsFile.InfFileName.find('$') == -1:\r
-                            InfPath = NormPath(FfsFile.InfFileName)\r
-                            if not os.path.exists(InfPath):\r
-                                EdkLogger.error('build', GENFDS_ERROR, "Non-existant Module %s !" % (FfsFile.InfFileName))\r
-\r
-                            PathClassObj = PathClass(FfsFile.InfFileName, self.WorkspaceDir)\r
-                            #\r
-                            # Here we just need to get FILE_GUID from INF file, use 'COMMON' as ARCH attribute. and use \r
-                            # BuildObject from one of AutoGenObjectList is enough.\r
-                            #\r
-                            InfObj = self.AutoGenObjectList[0].BuildDatabase.WorkspaceDb.BuildObject[PathClassObj, TAB_ARCH_COMMON, self.BuildTarget, self.ToolChain]\r
-                            if InfObj.Guid.upper() not in _GuidDict:\r
-                                _GuidDict[InfObj.Guid.upper()] = FfsFile\r
-                            else:\r
-                                EdkLogger.error("build",\r
-                                                FORMAT_INVALID,\r
-                                                "Duplicate GUID found for these lines: Line %d: %s and Line %d: %s. GUID: %s" % (FfsFile.CurrentLineNum,\r
-                                                                                                                               FfsFile.CurrentLineContent,\r
-                                                                                                                               _GuidDict[InfObj.Guid.upper()].CurrentLineNum,\r
-                                                                                                                               _GuidDict[InfObj.Guid.upper()].CurrentLineContent,\r
-                                                                                                                               InfObj.Guid.upper()),\r
-                                                ExtraData=self.FdfFile)\r
-                        InfFoundFlag = False\r
-\r
-                if FfsFile.NameGuid is not None:\r
-                    #\r
-                    # If the NameGuid reference a PCD name. \r
-                    # The style must match: PCD(xxxx.yyy)\r
-                    #\r
-                    if gPCDAsGuidPattern.match(FfsFile.NameGuid):\r
-                        #\r
-                        # Replace the PCD value.\r
-                        #\r
-                        _PcdName = FfsFile.NameGuid.lstrip("PCD(").rstrip(")")\r
-                        PcdFoundFlag = False\r
-                        for Pa in self.AutoGenObjectList:\r
-                            if not PcdFoundFlag:\r
-                                for PcdItem in Pa.AllPcdList:\r
-                                    if (PcdItem.TokenSpaceGuidCName + "." + PcdItem.TokenCName) == _PcdName:\r
-                                        #\r
-                                        # First convert from CFormatGuid to GUID string\r
-                                        #\r
-                                        _PcdGuidString = GuidStructureStringToGuidString(PcdItem.DefaultValue)\r
-\r
-                                        if not _PcdGuidString:\r
-                                            #\r
-                                            # Then try Byte array.\r
-                                            #\r
-                                            _PcdGuidString = GuidStructureByteArrayToGuidString(PcdItem.DefaultValue)\r
-\r
-                                        if not _PcdGuidString:\r
-                                            #\r
-                                            # Not Byte array or CFormat GUID, raise error.\r
-                                            #\r
-                                            EdkLogger.error("build",\r
-                                                            FORMAT_INVALID,\r
-                                                            "The format of PCD value is incorrect. PCD: %s , Value: %s\n" % (_PcdName, PcdItem.DefaultValue),\r
-                                                            ExtraData=self.FdfFile)\r
-\r
-                                        if _PcdGuidString.upper() not in _GuidDict:\r
-                                            _GuidDict[_PcdGuidString.upper()] = FfsFile\r
-                                            PcdFoundFlag = True\r
-                                            break\r
-                                        else:\r
-                                            EdkLogger.error("build",\r
-                                                            FORMAT_INVALID,\r
-                                                            "Duplicate GUID found for these lines: Line %d: %s and Line %d: %s. GUID: %s" % (FfsFile.CurrentLineNum,\r
-                                                                                                                                           FfsFile.CurrentLineContent,\r
-                                                                                                                                           _GuidDict[_PcdGuidString.upper()].CurrentLineNum,\r
-                                                                                                                                           _GuidDict[_PcdGuidString.upper()].CurrentLineContent,\r
-                                                                                                                                           FfsFile.NameGuid.upper()),\r
-                                                            ExtraData=self.FdfFile)\r
-\r
-                    if FfsFile.NameGuid.upper() not in _GuidDict:\r
-                        _GuidDict[FfsFile.NameGuid.upper()] = FfsFile\r
-                    else:\r
-                        #\r
-                        # Two raw file GUID conflict.\r
-                        #\r
-                        EdkLogger.error("build",\r
-                                        FORMAT_INVALID,\r
-                                        "Duplicate GUID found for these lines: Line %d: %s and Line %d: %s. GUID: %s" % (FfsFile.CurrentLineNum,\r
-                                                                                                                       FfsFile.CurrentLineContent,\r
-                                                                                                                       _GuidDict[FfsFile.NameGuid.upper()].CurrentLineNum,\r
-                                                                                                                       _GuidDict[FfsFile.NameGuid.upper()].CurrentLineContent,\r
-                                                                                                                       FfsFile.NameGuid.upper()),\r
-                                        ExtraData=self.FdfFile)\r
-\r
-\r
     def _CheckPcdDefineAndType(self):\r
         PcdTypeSet = {TAB_PCDS_FIXED_AT_BUILD,\r
             TAB_PCDS_PATCHABLE_IN_MODULE,\r
@@ -899,7 +770,7 @@ class WorkspaceAutoGen(AutoGen):
             for Pcd in Pa.Platform.Pcds:\r
                 PcdType = Pa.Platform.Pcds[Pcd].Type\r
 \r
-                # If no PCD type, this PCD comes from FDF \r
+                # If no PCD type, this PCD comes from FDF\r
                 if not PcdType:\r
                     continue\r
 \r
@@ -991,14 +862,14 @@ class WorkspaceAutoGen(AutoGen):
     ## Check the PCDs token value conflict in each DEC file.\r
     #\r
     # Will cause build break and raise error message while two PCDs conflict.\r
-    # \r
+    #\r
     # @return  None\r
     #\r
     def _CheckAllPcdsTokenValueConflict(self):\r
         for Pa in self.AutoGenObjectList:\r
             for Package in Pa.PackageList:\r
                 PcdList = Package.Pcds.values()\r
-                PcdList.sort(lambda x, y: cmp(int(x.TokenValue, 0), int(y.TokenValue, 0))) \r
+                PcdList.sort(key=lambda x: int(x.TokenValue, 0))\r
                 Count = 0\r
                 while (Count < len(PcdList) - 1) :\r
                     Item = PcdList[Count]\r
@@ -1019,7 +890,7 @@ class WorkspaceAutoGen(AutoGen):
                         #\r
                         # Sort same token value PCD list with TokenGuid and TokenCName\r
                         #\r
-                        SameTokenValuePcdList.sort(lambda x, y: cmp("%s.%s" % (x.TokenSpaceGuidCName, x.TokenCName), "%s.%s" % (y.TokenSpaceGuidCName, y.TokenCName)))\r
+                        SameTokenValuePcdList.sort(key=lambda x: "%s.%s" % (x.TokenSpaceGuidCName, x.TokenCName))\r
                         SameTokenValuePcdListCount = 0\r
                         while (SameTokenValuePcdListCount < len(SameTokenValuePcdList) - 1):\r
                             Flag = False\r
@@ -1044,7 +915,7 @@ class WorkspaceAutoGen(AutoGen):
                     Count += 1\r
 \r
                 PcdList = Package.Pcds.values()\r
-                PcdList.sort(lambda x, y: cmp("%s.%s" % (x.TokenSpaceGuidCName, x.TokenCName), "%s.%s" % (y.TokenSpaceGuidCName, y.TokenCName)))\r
+                PcdList.sort(key=lambda x: "%s.%s" % (x.TokenSpaceGuidCName, x.TokenCName))\r
                 Count = 0\r
                 while (Count < len(PcdList) - 1) :\r
                     Item = PcdList[Count]\r
@@ -1116,27 +987,25 @@ class WorkspaceAutoGen(AutoGen):
 class PlatformAutoGen(AutoGen):\r
     # call super().__init__ then call the worker function with different parameter count\r
     def __init__(self, Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs):\r
-        try:\r
-            self._Init\r
-        except:\r
+        if not hasattr(self, "_Init"):\r
             super(PlatformAutoGen, self).__init__(self, Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs)\r
             self._InitWorker(Workspace, MetaFile, Target, Toolchain, Arch)\r
             self._Init = True\r
     #\r
-    # Used to store all PCDs for both PEI and DXE phase, in order to generate \r
+    # Used to store all PCDs for both PEI and DXE phase, in order to generate\r
     # correct PCD database\r
-    # \r
+    #\r
     _DynaPcdList_ = []\r
     _NonDynaPcdList_ = []\r
     _PlatformPcds = {}\r
-    \r
+\r
     #\r
-    # The priority list while override build option \r
+    # The priority list while override build option\r
     #\r
     PrioList = {"0x11111"  : 16,     #  TARGET_TOOLCHAIN_ARCH_COMMANDTYPE_ATTRIBUTE (Highest)\r
                 "0x01111"  : 15,     #  ******_TOOLCHAIN_ARCH_COMMANDTYPE_ATTRIBUTE\r
                 "0x10111"  : 14,     #  TARGET_*********_ARCH_COMMANDTYPE_ATTRIBUTE\r
-                "0x00111"  : 13,     #  ******_*********_ARCH_COMMANDTYPE_ATTRIBUTE \r
+                "0x00111"  : 13,     #  ******_*********_ARCH_COMMANDTYPE_ATTRIBUTE\r
                 "0x11011"  : 12,     #  TARGET_TOOLCHAIN_****_COMMANDTYPE_ATTRIBUTE\r
                 "0x01011"  : 11,     #  ******_TOOLCHAIN_****_COMMANDTYPE_ATTRIBUTE\r
                 "0x10011"  : 10,     #  TARGET_*********_****_COMMANDTYPE_ATTRIBUTE\r
@@ -1222,7 +1091,7 @@ class PlatformAutoGen(AutoGen):
             for Inf in self._AsBuildInfList:\r
                 InfClass = PathClass(NormPath(Inf), GlobalData.gWorkspace, self.Arch)\r
                 M = self.BuildDatabase[InfClass, self.Arch, self.BuildTarget, self.ToolChain]\r
-                if not M.IsSupportedArch:\r
+                if not M.IsBinaryModule:\r
                     continue\r
                 self._AsBuildModuleList.append(InfClass)\r
         # get library/modules for build\r
@@ -1288,26 +1157,31 @@ class PlatformAutoGen(AutoGen):
     #\r
     def CollectFixedAtBuildPcds(self):\r
         for LibAuto in self.LibraryAutoGenList:\r
-            FixedAtBuildPcds = {}  \r
-            ShareFixedAtBuildPcdsSameValue = {} \r
-            for Module in LibAuto._ReferenceModules:                \r
-                for Pcd in Module.FixedAtBuildPcds + LibAuto.FixedAtBuildPcds:\r
-                    key = ".".join((Pcd.TokenSpaceGuidCName,Pcd.TokenCName))  \r
+            FixedAtBuildPcds = {}\r
+            ShareFixedAtBuildPcdsSameValue = {}\r
+            for Module in LibAuto.ReferenceModules:\r
+                for Pcd in set(Module.FixedAtBuildPcds + LibAuto.FixedAtBuildPcds):\r
+                    DefaultValue = Pcd.DefaultValue\r
+                    # Cover the case: DSC component override the Pcd value and the Pcd only used in one Lib\r
+                    if Pcd in Module.LibraryPcdList:\r
+                        Index = Module.LibraryPcdList.index(Pcd)\r
+                        DefaultValue = Module.LibraryPcdList[Index].DefaultValue\r
+                    key = ".".join((Pcd.TokenSpaceGuidCName, Pcd.TokenCName))\r
                     if key not in FixedAtBuildPcds:\r
                         ShareFixedAtBuildPcdsSameValue[key] = True\r
-                        FixedAtBuildPcds[key] = Pcd.DefaultValue\r
+                        FixedAtBuildPcds[key] = DefaultValue\r
                     else:\r
-                        if FixedAtBuildPcds[key] != Pcd.DefaultValue:\r
-                            ShareFixedAtBuildPcdsSameValue[key] = False      \r
+                        if FixedAtBuildPcds[key] != DefaultValue:\r
+                            ShareFixedAtBuildPcdsSameValue[key] = False\r
             for Pcd in LibAuto.FixedAtBuildPcds:\r
-                key = ".".join((Pcd.TokenSpaceGuidCName,Pcd.TokenCName))\r
-                if (Pcd.TokenCName,Pcd.TokenSpaceGuidCName) not in self.NonDynamicPcdDict:\r
+                key = ".".join((Pcd.TokenSpaceGuidCName, Pcd.TokenCName))\r
+                if (Pcd.TokenCName, Pcd.TokenSpaceGuidCName) not in self.NonDynamicPcdDict:\r
                     continue\r
                 else:\r
-                    DscPcd = self.NonDynamicPcdDict[(Pcd.TokenCName,Pcd.TokenSpaceGuidCName)]\r
+                    DscPcd = self.NonDynamicPcdDict[(Pcd.TokenCName, Pcd.TokenSpaceGuidCName)]\r
                     if DscPcd.Type != TAB_PCDS_FIXED_AT_BUILD:\r
                         continue\r
-                if key in ShareFixedAtBuildPcdsSameValue and ShareFixedAtBuildPcdsSameValue[key]:                    \r
+                if key in ShareFixedAtBuildPcdsSameValue and ShareFixedAtBuildPcdsSameValue[key]:\r
                     LibAuto.ConstPcd[key] = FixedAtBuildPcds[key]\r
 \r
     def CollectVariables(self, DynamicPcdSet):\r
@@ -1324,12 +1198,12 @@ class PlatformAutoGen(AutoGen):
                         break\r
 \r
 \r
-        VariableInfo = VariableMgr(self.DscBuildDataObj._GetDefaultStores(),self.DscBuildDataObj._GetSkuIds())\r
+        VariableInfo = VariableMgr(self.DscBuildDataObj._GetDefaultStores(), self.DscBuildDataObj._GetSkuIds())\r
         VariableInfo.SetVpdRegionMaxSize(VpdRegionSize)\r
         VariableInfo.SetVpdRegionOffset(VpdRegionBase)\r
         Index = 0\r
         for Pcd in DynamicPcdSet:\r
-            pcdname = ".".join((Pcd.TokenSpaceGuidCName,Pcd.TokenCName))\r
+            pcdname = ".".join((Pcd.TokenSpaceGuidCName, Pcd.TokenCName))\r
             for SkuName in Pcd.SkuInfoList:\r
                 Sku = Pcd.SkuInfoList[SkuName]\r
                 SkuId = Sku.SkuId\r
@@ -1339,11 +1213,11 @@ class PlatformAutoGen(AutoGen):
                     VariableGuidStructure = Sku.VariableGuidValue\r
                     VariableGuid = GuidStructureStringToGuidString(VariableGuidStructure)\r
                     for StorageName in Sku.DefaultStoreDict:\r
-                        VariableInfo.append_variable(var_info(Index,pcdname,StorageName,SkuName, StringToArray(Sku.VariableName),VariableGuid, Sku.VariableOffset, Sku.VariableAttribute , Sku.HiiDefaultValue,Sku.DefaultStoreDict[StorageName],Pcd.DatumType))\r
+                        VariableInfo.append_variable(var_info(Index, pcdname, StorageName, SkuName, StringToArray(Sku.VariableName), VariableGuid, Sku.VariableOffset, Sku.VariableAttribute, Sku.HiiDefaultValue, Sku.DefaultStoreDict[StorageName], Pcd.DatumType))\r
             Index += 1\r
         return VariableInfo\r
 \r
-    def UpdateNVStoreMaxSize(self,OrgVpdFile):\r
+    def UpdateNVStoreMaxSize(self, OrgVpdFile):\r
         if self.VariableInfo:\r
             VpdMapFilePath = os.path.join(self.BuildDir, TAB_FV_DIRECTORY, "%s.map" % self.Platform.VpdToolGuid)\r
             PcdNvStoreDfBuffer = [item for item in self._DynamicPcdList if item.TokenCName == "PcdNvStoreDefaultValueBuffer" and item.TokenSpaceGuidCName == "gEfiMdeModulePkgTokenSpaceGuid"]\r
@@ -1356,7 +1230,7 @@ class PlatformAutoGen(AutoGen):
                 else:\r
                     EdkLogger.error("build", FILE_READ_FAILURE, "Can not find VPD map file %s to fix up VPD offset." % VpdMapFilePath)\r
 \r
-                NvStoreOffset = int(NvStoreOffset,16) if NvStoreOffset.upper().startswith("0X") else int(NvStoreOffset)\r
+                NvStoreOffset = int(NvStoreOffset, 16) if NvStoreOffset.upper().startswith("0X") else int(NvStoreOffset)\r
                 default_skuobj = PcdNvStoreDfBuffer[0].SkuInfoList.get(TAB_DEFAULT)\r
                 maxsize = self.VariableInfo.VpdRegionSize  - NvStoreOffset if self.VariableInfo.VpdRegionSize else len(default_skuobj.DefaultValue.split(","))\r
                 var_data = self.VariableInfo.PatchNVStoreDefaultMaxSize(maxsize)\r
@@ -1404,7 +1278,7 @@ class PlatformAutoGen(AutoGen):
         for F in self.Platform.Modules.keys():\r
             M = ModuleAutoGen(self.Workspace, F, self.BuildTarget, self.ToolChain, self.Arch, self.MetaFile)\r
             #GuidValue.update(M.Guids)\r
-            \r
+\r
             self.Platform.Modules[F].M = M\r
 \r
             for PcdFromModule in M.ModulePcdList + M.LibraryPcdList:\r
@@ -1416,27 +1290,27 @@ class PlatformAutoGen(AutoGen):
                 if M.IsBinaryModule == True:\r
                     PcdFromModule.IsFromBinaryInf = True\r
 \r
-                # Check the PCD from DSC or not \r
+                # Check the PCD from DSC or not\r
                 PcdFromModule.IsFromDsc = (PcdFromModule.TokenCName, PcdFromModule.TokenSpaceGuidCName) in self.Platform.Pcds\r
 \r
                 if PcdFromModule.Type in PCD_DYNAMIC_TYPE_SET or PcdFromModule.Type in PCD_DYNAMIC_EX_TYPE_SET:\r
                     if F.Path not in FdfModuleList:\r
-                        # If one of the Source built modules listed in the DSC is not listed \r
-                        # in FDF modules, and the INF lists a PCD can only use the PcdsDynamic \r
-                        # access method (it is only listed in the DEC file that declares the \r
+                        # If one of the Source built modules listed in the DSC is not listed\r
+                        # in FDF modules, and the INF lists a PCD can only use the PcdsDynamic\r
+                        # access method (it is only listed in the DEC file that declares the\r
                         # PCD as PcdsDynamic), then build tool will report warning message\r
-                        # notify the PI that they are attempting to build a module that must \r
-                        # be included in a flash image in order to be functional. These Dynamic \r
-                        # PCD will not be added into the Database unless it is used by other \r
+                        # notify the PI that they are attempting to build a module that must\r
+                        # be included in a flash image in order to be functional. These Dynamic\r
+                        # PCD will not be added into the Database unless it is used by other\r
                         # modules that are included in the FDF file.\r
                         if PcdFromModule.Type in PCD_DYNAMIC_TYPE_SET and \\r
                             PcdFromModule.IsFromBinaryInf == False:\r
                             # Print warning message to let the developer make a determine.\r
                             continue\r
-                        # If one of the Source built modules listed in the DSC is not listed in \r
-                        # FDF modules, and the INF lists a PCD can only use the PcdsDynamicEx \r
-                        # access method (it is only listed in the DEC file that declares the \r
-                        # PCD as PcdsDynamicEx), then DO NOT break the build; DO NOT add the \r
+                        # If one of the Source built modules listed in the DSC is not listed in\r
+                        # FDF modules, and the INF lists a PCD can only use the PcdsDynamicEx\r
+                        # access method (it is only listed in the DEC file that declares the\r
+                        # PCD as PcdsDynamicEx), then DO NOT break the build; DO NOT add the\r
                         # PCD to the Platform's PCD Database.\r
                         if PcdFromModule.Type in PCD_DYNAMIC_EX_TYPE_SET:\r
                             continue\r
@@ -1464,15 +1338,15 @@ class PlatformAutoGen(AutoGen):
                         PcdFromModule.Pending = False\r
                         self._NonDynaPcdList_.append (PcdFromModule)\r
         DscModuleSet = {os.path.normpath(ModuleInf.Path) for ModuleInf in self.Platform.Modules}\r
-        # add the PCD from modules that listed in FDF but not in DSC to Database \r
+        # add the PCD from modules that listed in FDF but not in DSC to Database\r
         for InfName in FdfModuleList:\r
             if InfName not in DscModuleSet:\r
                 InfClass = PathClass(InfName)\r
                 M = self.BuildDatabase[InfClass, self.Arch, self.BuildTarget, self.ToolChain]\r
-                # If a module INF in FDF but not in current arch's DSC module list, it must be module (either binary or source) \r
-                # for different Arch. PCDs in source module for different Arch is already added before, so skip the source module here. \r
-                # For binary module, if in current arch, we need to list the PCDs into database.   \r
-                if not M.IsSupportedArch:\r
+                # If a module INF in FDF but not in current arch's DSC module list, it must be module (either binary or source)\r
+                # for different Arch. PCDs in source module for different Arch is already added before, so skip the source module here.\r
+                # For binary module, if in current arch, we need to list the PCDs into database.\r
+                if not M.IsBinaryModule:\r
                     continue\r
                 # Override the module PCD setting by platform setting\r
                 ModulePcdList = self.ApplyPcdSetting(M, M.Pcds)\r
@@ -1496,20 +1370,20 @@ class PlatformAutoGen(AutoGen):
                         self._NonDynaPcdList_.append(PcdFromModule)\r
                     if PcdFromModule in self._DynaPcdList_ and PcdFromModule.Phase == 'PEI' and PcdFromModule.Type in PCD_DYNAMIC_EX_TYPE_SET:\r
                         # Overwrite the phase of any the same PCD existing, if Phase is PEI.\r
-                        # It is to solve the case that a dynamic PCD used by a PEM module/PEI \r
+                        # It is to solve the case that a dynamic PCD used by a PEM module/PEI\r
                         # module & DXE module at a same time.\r
                         # Overwrite the type of the PCDs in source INF by the type of AsBuild\r
-                        # INF file as DynamicEx. \r
+                        # INF file as DynamicEx.\r
                         Index = self._DynaPcdList_.index(PcdFromModule)\r
                         self._DynaPcdList_[Index].Phase = PcdFromModule.Phase\r
                         self._DynaPcdList_[Index].Type = PcdFromModule.Type\r
         for PcdFromModule in self._NonDynaPcdList_:\r
-            # If a PCD is not listed in the DSC file, but binary INF files used by \r
-            # this platform all (that use this PCD) list the PCD in a [PatchPcds] \r
-            # section, AND all source INF files used by this platform the build \r
-            # that use the PCD list the PCD in either a [Pcds] or [PatchPcds] \r
+            # If a PCD is not listed in the DSC file, but binary INF files used by\r
+            # this platform all (that use this PCD) list the PCD in a [PatchPcds]\r
+            # section, AND all source INF files used by this platform the build\r
+            # that use the PCD list the PCD in either a [Pcds] or [PatchPcds]\r
             # section, then the tools must NOT add the PCD to the Platform's PCD\r
-            # Database; the build must assign the access method for this PCD as \r
+            # Database; the build must assign the access method for this PCD as\r
             # PcdsPatchableInModule.\r
             if PcdFromModule not in self._DynaPcdList_:\r
                 continue\r
@@ -1532,7 +1406,7 @@ class PlatformAutoGen(AutoGen):
         self._DynamicPcdList = self._DynaPcdList_\r
         #\r
         # Sort dynamic PCD list to:\r
-        # 1) If PCD's datum type is VOID* and value is unicode string which starts with L, the PCD item should \r
+        # 1) If PCD's datum type is VOID* and value is unicode string which starts with L, the PCD item should\r
         #    try to be put header of dynamicd List\r
         # 2) If PCD is HII type, the PCD item should be put after unicode type PCD\r
         #\r
@@ -1553,7 +1427,7 @@ class PlatformAutoGen(AutoGen):
             if self._PlatformPcds[item].DatumType and self._PlatformPcds[item].DatumType not in [TAB_UINT8, TAB_UINT16, TAB_UINT32, TAB_UINT64, TAB_VOID, "BOOLEAN"]:\r
                 self._PlatformPcds[item].DatumType = TAB_VOID\r
 \r
-        if (self.Workspace.ArchList[-1] == self.Arch): \r
+        if (self.Workspace.ArchList[-1] == self.Arch):\r
             for Pcd in self._DynamicPcdList:\r
                 # just pick the a value to determine whether is unicode string type\r
                 Sku = Pcd.SkuInfoList.values()[0]\r
@@ -1568,7 +1442,7 @@ class PlatformAutoGen(AutoGen):
                     VpdPcdDict[(Pcd.TokenCName, Pcd.TokenSpaceGuidCName)] = Pcd\r
 \r
             #Collect DynamicHii PCD values and assign it to DynamicExVpd PCD gEfiMdeModulePkgTokenSpaceGuid.PcdNvStoreDefaultValueBuffer\r
-            PcdNvStoreDfBuffer = VpdPcdDict.get(("PcdNvStoreDefaultValueBuffer","gEfiMdeModulePkgTokenSpaceGuid"))\r
+            PcdNvStoreDfBuffer = VpdPcdDict.get(("PcdNvStoreDefaultValueBuffer", "gEfiMdeModulePkgTokenSpaceGuid"))\r
             if PcdNvStoreDfBuffer:\r
                 self.VariableInfo = self.CollectVariables(self._DynamicPcdList)\r
                 vardump = self.VariableInfo.dump()\r
@@ -1594,10 +1468,10 @@ class PlatformAutoGen(AutoGen):
                         PcdValue = DefaultSku.DefaultValue\r
                         if PcdValue not in SkuValueMap:\r
                             SkuValueMap[PcdValue] = []\r
-                            VpdFile.Add(Pcd, TAB_DEFAULT,DefaultSku.VpdOffset)\r
+                            VpdFile.Add(Pcd, TAB_DEFAULT, DefaultSku.VpdOffset)\r
                         SkuValueMap[PcdValue].append(DefaultSku)\r
 \r
-                    for (SkuName,Sku) in Pcd.SkuInfoList.items():\r
+                    for (SkuName, Sku) in Pcd.SkuInfoList.items():\r
                         Sku.VpdOffset = Sku.VpdOffset.strip()\r
                         PcdValue = Sku.DefaultValue\r
                         if PcdValue == "":\r
@@ -1623,7 +1497,7 @@ class PlatformAutoGen(AutoGen):
                                     EdkLogger.error("build", FORMAT_INVALID, 'The offset value of PCD %s.%s should be %s-byte aligned.' % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName, Alignment))\r
                         if PcdValue not in SkuValueMap:\r
                             SkuValueMap[PcdValue] = []\r
-                            VpdFile.Add(Pcd, SkuName,Sku.VpdOffset)\r
+                            VpdFile.Add(Pcd, SkuName, Sku.VpdOffset)\r
                         SkuValueMap[PcdValue].append(Sku)\r
                         # if the offset of a VPD is *, then it need to be fixed up by third party tool.\r
                         if not NeedProcessVpdMapFile and Sku.VpdOffset == "*":\r
@@ -1636,7 +1510,7 @@ class PlatformAutoGen(AutoGen):
             #\r
             # Fix the PCDs define in VPD PCD section that never referenced by module.\r
             # An example is PCD for signature usage.\r
-            #            \r
+            #\r
             for DscPcd in PlatformPcds:\r
                 DscPcdEntry = self._PlatformPcds[DscPcd]\r
                 if DscPcdEntry.Type in [TAB_PCDS_DYNAMIC_VPD, TAB_PCDS_DYNAMIC_EX_VPD]:\r
@@ -1655,11 +1529,11 @@ class PlatformAutoGen(AutoGen):
                             SkuObjList = DscPcdEntry.SkuInfoList.items()\r
                             DefaultSku = DscPcdEntry.SkuInfoList.get(TAB_DEFAULT)\r
                             if DefaultSku:\r
-                                defaultindex = SkuObjList.index((TAB_DEFAULT,DefaultSku))\r
-                                SkuObjList[0],SkuObjList[defaultindex] = SkuObjList[defaultindex],SkuObjList[0]\r
-                            for (SkuName,Sku) in SkuObjList:\r
-                                Sku.VpdOffset = Sku.VpdOffset.strip() \r
-                                \r
+                                defaultindex = SkuObjList.index((TAB_DEFAULT, DefaultSku))\r
+                                SkuObjList[0], SkuObjList[defaultindex] = SkuObjList[defaultindex], SkuObjList[0]\r
+                            for (SkuName, Sku) in SkuObjList:\r
+                                Sku.VpdOffset = Sku.VpdOffset.strip()\r
+\r
                                 # Need to iterate DEC pcd information to get the value & datumtype\r
                                 for eachDec in self.PackageList:\r
                                     for DecPcd in eachDec.Pcds:\r
@@ -1670,8 +1544,8 @@ class PlatformAutoGen(AutoGen):
                                             EdkLogger.warn("build", "Unreferenced vpd pcd used!",\r
                                                             File=self.MetaFile, \\r
                                                             ExtraData = "PCD: %s.%s used in the DSC file %s is unreferenced." \\r
-                                                            %(DscPcdEntry.TokenSpaceGuidCName, DscPcdEntry.TokenCName, self.Platform.MetaFile.Path))  \r
-                                                                                  \r
+                                                            %(DscPcdEntry.TokenSpaceGuidCName, DscPcdEntry.TokenCName, self.Platform.MetaFile.Path))\r
+\r
                                             DscPcdEntry.DatumType    = DecPcdEntry.DatumType\r
                                             DscPcdEntry.DefaultValue = DecPcdEntry.DefaultValue\r
                                             DscPcdEntry.TokenValue = DecPcdEntry.TokenValue\r
@@ -1679,7 +1553,7 @@ class PlatformAutoGen(AutoGen):
                                             # Only fix the value while no value provided in DSC file.\r
                                             if not Sku.DefaultValue:\r
                                                 DscPcdEntry.SkuInfoList[DscPcdEntry.SkuInfoList.keys()[0]].DefaultValue = DecPcdEntry.DefaultValue\r
-                                                                                                                    \r
+\r
                                 if DscPcdEntry not in self._DynamicPcdList:\r
                                     self._DynamicPcdList.append(DscPcdEntry)\r
                                 Sku.VpdOffset = Sku.VpdOffset.strip()\r
@@ -1707,10 +1581,10 @@ class PlatformAutoGen(AutoGen):
                                             EdkLogger.error("build", FORMAT_INVALID, 'The offset value of PCD %s.%s should be %s-byte aligned.' % (DscPcdEntry.TokenSpaceGuidCName, DscPcdEntry.TokenCName, Alignment))\r
                                 if PcdValue not in SkuValueMap:\r
                                     SkuValueMap[PcdValue] = []\r
-                                    VpdFile.Add(DscPcdEntry, SkuName,Sku.VpdOffset)\r
+                                    VpdFile.Add(DscPcdEntry, SkuName, Sku.VpdOffset)\r
                                 SkuValueMap[PcdValue].append(Sku)\r
                                 if not NeedProcessVpdMapFile and Sku.VpdOffset == "*":\r
-                                    NeedProcessVpdMapFile = True \r
+                                    NeedProcessVpdMapFile = True\r
                             if DscPcdEntry.DatumType == TAB_VOID and PcdValue.startswith("L"):\r
                                 UnicodePcdArray.add(DscPcdEntry)\r
                             elif len(Sku.VariableName) > 0:\r
@@ -1722,7 +1596,7 @@ class PlatformAutoGen(AutoGen):
                             VpdSkuMap[DscPcd] = SkuValueMap\r
             if (self.Platform.FlashDefinition is None or self.Platform.FlashDefinition == '') and \\r
                VpdFile.GetCount() != 0:\r
-                EdkLogger.error("build", ATTRIBUTE_NOT_AVAILABLE, \r
+                EdkLogger.error("build", ATTRIBUTE_NOT_AVAILABLE,\r
                                 "Fail to get FLASH_DEFINITION definition in DSC file %s which is required when DSC contains VPD PCD." % str(self.Platform.MetaFile))\r
 \r
             if VpdFile.GetCount() != 0:\r
@@ -1773,17 +1647,18 @@ class PlatformAutoGen(AutoGen):
         self._DynamicPcdList.extend(list(UnicodePcdArray))\r
         self._DynamicPcdList.extend(list(HiiPcdArray))\r
         self._DynamicPcdList.extend(list(OtherPcdArray))\r
-        allskuset = [(SkuName,Sku.SkuId) for pcd in self._DynamicPcdList for (SkuName,Sku) in pcd.SkuInfoList.items()]\r
+        allskuset = [(SkuName, Sku.SkuId) for pcd in self._DynamicPcdList for (SkuName, Sku) in pcd.SkuInfoList.items()]\r
         for pcd in self._DynamicPcdList:\r
             if len(pcd.SkuInfoList) == 1:\r
-                for (SkuName,SkuId) in allskuset:\r
-                    if type(SkuId) in (str,unicode) and eval(SkuId) == 0 or SkuId == 0:\r
+                for (SkuName, SkuId) in allskuset:\r
+                    if type(SkuId) in (str, unicode) and eval(SkuId) == 0 or SkuId == 0:\r
                         continue\r
                     pcd.SkuInfoList[SkuName] = copy.deepcopy(pcd.SkuInfoList[TAB_DEFAULT])\r
                     pcd.SkuInfoList[SkuName].SkuId = SkuId\r
+                    pcd.SkuInfoList[SkuName].SkuIdName = SkuName\r
         self.AllPcdList = self._NonDynamicPcdList + self._DynamicPcdList\r
 \r
-    def FixVpdOffset(self,VpdFile ):\r
+    def FixVpdOffset(self, VpdFile ):\r
         FvPath = os.path.join(self.BuildDir, TAB_FV_DIRECTORY)\r
         if not os.path.exists(FvPath):\r
             try:\r
@@ -1797,8 +1672,8 @@ class PlatformAutoGen(AutoGen):
             # retrieve BPDG tool's path from tool_def.txt according to VPD_TOOL_GUID defined in DSC file.\r
             BPDGToolName = None\r
             for ToolDef in self.ToolDefinition.values():\r
-                if ToolDef.has_key(TAB_GUID) and ToolDef[TAB_GUID] == self.Platform.VpdToolGuid:\r
-                    if not ToolDef.has_key("PATH"):\r
+                if TAB_GUID in ToolDef and ToolDef[TAB_GUID] == self.Platform.VpdToolGuid:\r
+                    if "PATH" not in ToolDef:\r
                         EdkLogger.error("build", ATTRIBUTE_NOT_AVAILABLE, "PATH attribute was not provided for BPDG guid tool %s in tools_def.txt" % self.Platform.VpdToolGuid)\r
                     BPDGToolName = ToolDef["PATH"]\r
                     break\r
@@ -1968,7 +1843,7 @@ class PlatformAutoGen(AutoGen):
                or not ToolDefinition[TAB_TOD_DEFINES_FAMILY][self.ToolChain]:\r
                 EdkLogger.verbose("No tool chain family found in configuration for %s. Default to MSFT." \\r
                                    % self.ToolChain)\r
-                self._ToolChainFamily = "MSFT"\r
+                self._ToolChainFamily = TAB_COMPILER_MSFT\r
             else:\r
                 self._ToolChainFamily = ToolDefinition[TAB_TOD_DEFINES_FAMILY][self.ToolChain]\r
         return self._ToolChainFamily\r
@@ -1981,7 +1856,7 @@ class PlatformAutoGen(AutoGen):
                or not ToolDefinition[TAB_TOD_DEFINES_BUILDRULEFAMILY][self.ToolChain]:\r
                 EdkLogger.verbose("No tool chain family found in configuration for %s. Default to MSFT." \\r
                                    % self.ToolChain)\r
-                self._BuildRuleFamily = "MSFT"\r
+                self._BuildRuleFamily = TAB_COMPILER_MSFT\r
             else:\r
                 self._BuildRuleFamily = ToolDefinition[TAB_TOD_DEFINES_BUILDRULEFAMILY][self.ToolChain]\r
         return self._BuildRuleFamily\r
@@ -2049,7 +1924,7 @@ class PlatformAutoGen(AutoGen):
         if self._NonDynamicPcdDict:\r
             return self._NonDynamicPcdDict\r
         for Pcd in self.NonDynamicPcdList:\r
-            self._NonDynamicPcdDict[(Pcd.TokenCName,Pcd.TokenSpaceGuidCName)] = Pcd\r
+            self._NonDynamicPcdDict[(Pcd.TokenCName, Pcd.TokenSpaceGuidCName)] = Pcd\r
         return self._NonDynamicPcdDict\r
 \r
     ## Get list of non-dynamic PCDs\r
@@ -2070,9 +1945,9 @@ class PlatformAutoGen(AutoGen):
             self._PcdTokenNumber = OrderedDict()\r
             TokenNumber = 1\r
             #\r
-            # Make the Dynamic and DynamicEx PCD use within different TokenNumber area. \r
+            # Make the Dynamic and DynamicEx PCD use within different TokenNumber area.\r
             # Such as:\r
-            # \r
+            #\r
             # Dynamic PCD:\r
             # TokenNumber 0 ~ 10\r
             # DynamicEx PCD:\r
@@ -2125,8 +2000,8 @@ class PlatformAutoGen(AutoGen):
             for La in Ma.LibraryAutoGenList:\r
                 if La not in self._LibraryAutoGenList:\r
                     self._LibraryAutoGenList.append(La)\r
-                if Ma not in La._ReferenceModules:\r
-                    La._ReferenceModules.append(Ma)\r
+                if Ma not in La.ReferenceModules:\r
+                    La.ReferenceModules.append(Ma)\r
 \r
     ## Summarize ModuleAutoGen objects of all modules to be built for this platform\r
     def _GetModuleAutoGenList(self):\r
@@ -2220,7 +2095,7 @@ class PlatformAutoGen(AutoGen):
             if ToPcd.DefaultValue:\r
                 try:\r
                     ToPcd.DefaultValue = ValueExpressionEx(ToPcd.DefaultValue, ToPcd.DatumType, self._GuidDict)(True)\r
-                except BadExpression, Value:\r
+                except BadExpression as Value:\r
                     EdkLogger.error('Parser', FORMAT_INVALID, 'PCD [%s.%s] Value "%s", %s' %(ToPcd.TokenSpaceGuidCName, ToPcd.TokenCName, ToPcd.DefaultValue, Value),\r
                                         File=self.MetaFile)\r
 \r
@@ -2387,7 +2262,7 @@ class PlatformAutoGen(AutoGen):
     #   @param  Options     Options to be expanded\r
     #\r
     #   @retval options     Options expanded\r
-    #      \r
+    #\r
     def _ExpandBuildOption(self, Options, ModuleStyle=None):\r
         BuildOptions = {}\r
         FamilyMatch  = False\r
@@ -2413,9 +2288,9 @@ class PlatformAutoGen(AutoGen):
                     if OverrideList.get(Key[1]) is not None:\r
                         OverrideList.pop(Key[1])\r
                     OverrideList[Key[1]] = Options[Key]\r
-        \r
+\r
         #\r
-        # Use the highest priority value. \r
+        # Use the highest priority value.\r
         #\r
         if (len(OverrideList) >= 2):\r
             KeyList = OverrideList.keys()\r
@@ -2426,7 +2301,7 @@ class PlatformAutoGen(AutoGen):
                     NextKey = KeyList[Index1 + Index + 1]\r
                     #\r
                     # Compare two Key, if one is included by another, choose the higher priority one\r
-                    #                    \r
+                    #\r
                     Target2, ToolChain2, Arch2, CommandType2, Attr2 = NextKey.split("_")\r
                     if (Target1 == Target2 or Target1 == "*" or Target2 == "*") and\\r
                         (ToolChain1 == ToolChain2 or ToolChain1 == "*" or ToolChain2 == "*") and\\r
@@ -2440,7 +2315,7 @@ class PlatformAutoGen(AutoGen):
                         else:\r
                             if Options.get((self.BuildRuleFamily, NowKey)) is not None:\r
                                 Options.pop((self.BuildRuleFamily, NowKey))\r
-                                                           \r
+\r
         for Key in Options:\r
             if ModuleStyle is not None and len (Key) > 2:\r
                 # Check Module style is EDK or EDKII.\r
@@ -2609,6 +2484,11 @@ def ExtendCopyDictionaryLists(CopyToDict, CopyFromDict):
     for Key in CopyFromDict:\r
         CopyToDict[Key].extend(CopyFromDict[Key])\r
 \r
+# Create a directory specified by a set of path elements and return the full path\r
+def _MakeDir(PathList):\r
+    RetVal = path.join(*PathList)\r
+    CreateDirectory(RetVal)\r
+    return RetVal\r
 \r
 ## ModuleAutoGen class\r
 #\r
@@ -2619,26 +2499,23 @@ def ExtendCopyDictionaryLists(CopyToDict, CopyFromDict):
 class ModuleAutoGen(AutoGen):\r
     # call super().__init__ then call the worker function with different parameter count\r
     def __init__(self, Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs):\r
-        try:\r
-            self._Init\r
-        except:\r
+        if not hasattr(self, "_Init"):\r
             super(ModuleAutoGen, self).__init__(Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs)\r
             self._InitWorker(Workspace, MetaFile, Target, Toolchain, Arch, *args)\r
             self._Init = True\r
 \r
-    ## Cache the timestamps of metafiles of every module in a class variable\r
+    ## Cache the timestamps of metafiles of every module in a class attribute\r
     #\r
     TimeDict = {}\r
 \r
     def __new__(cls, Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs):\r
-        obj = super(ModuleAutoGen, cls).__new__(cls, Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs)\r
         # check if this module is employed by active platform\r
         if not PlatformAutoGen(Workspace, args[0], Target, Toolchain, Arch).ValidModule(MetaFile):\r
             EdkLogger.verbose("Module [%s] for [%s] is not employed by active platform\n" \\r
                               % (MetaFile, Arch))\r
             return None\r
-        return obj\r
-            \r
+        return super(ModuleAutoGen, cls).__new__(cls, Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs)\r
+\r
     ## Initialize ModuleAutoGen\r
     #\r
     #   @param      Workspace           EdkIIWorkspaceBuild object\r
@@ -2672,7 +2549,6 @@ class ModuleAutoGen(AutoGen):
         self.ToolChainFamily = self.PlatformInfo.ToolChainFamily\r
         self.BuildRuleFamily = self.PlatformInfo.BuildRuleFamily\r
 \r
-        self.IsMakeFileCreated = False\r
         self.IsCodeFileCreated = False\r
         self.IsAsBuiltInfCreated = False\r
         self.DepexGenerated = False\r
@@ -2681,87 +2557,45 @@ class ModuleAutoGen(AutoGen):
         self.BuildRuleOrder = None\r
         self.BuildTime      = 0\r
 \r
-        self._Module          = None\r
-        self._Name            = None\r
-        self._Guid            = None\r
-        self._Version         = None\r
-        self._ModuleType      = None\r
-        self._ComponentType   = None\r
-        self._PcdIsDriver     = None\r
-        self._AutoGenVersion  = None\r
-        self._LibraryFlag     = None\r
-        self._CustomMakefile  = None\r
-        self._Macro           = None\r
-\r
-        self._BuildDir        = None\r
-        self._OutputDir       = None\r
-        self._FfsOutputDir    = None\r
-        self._DebugDir        = None\r
-        self._MakeFileDir     = None\r
-\r
-        self._IncludePathList = None\r
-        self._AutoGenFileList = None\r
-        self._UnicodeFileList = None\r
-        self._VfrFileList = None\r
-        self._IdfFileList = None\r
-        self._SourceFileList  = None\r
-        self._ObjectFileList  = None\r
-        self._BinaryFileList  = None\r
-\r
-        self._DependentPackageList    = None\r
-        self._DependentLibraryList    = None\r
-        self._LibraryAutoGenList      = None\r
-        self._DerivedPackageList      = None\r
-        self._ModulePcdList           = None\r
-        self._LibraryPcdList          = None\r
         self._PcdComments = OrderedListDict()\r
-        self._GuidList                = None\r
-        self._GuidsUsedByPcd = None\r
         self._GuidComments = OrderedListDict()\r
-        self._ProtocolList            = None\r
         self._ProtocolComments = OrderedListDict()\r
-        self._PpiList                 = None\r
         self._PpiComments = OrderedListDict()\r
-        self._DepexDict               = None\r
-        self._DepexExpressionDict     = None\r
-        self._BuildOption             = None\r
-        self._BuildOptionIncPathList  = None\r
         self._BuildTargets            = None\r
         self._IntroBuildTargetList    = None\r
         self._FinalBuildTargetList    = None\r
         self._FileTypes               = None\r
-        self._BuildRules              = None\r
-\r
-        self._TimeStampPath           = None\r
 \r
         self.AutoGenDepSet = set()\r
-\r
-        \r
-        ## The Modules referenced to this Library\r
-        #  Only Library has this attribute\r
-        self._ReferenceModules        = []        \r
-        \r
-        ## Store the FixedAtBuild Pcds\r
-        #  \r
-        self._FixedAtBuildPcds         = []\r
+        self.ReferenceModules = []\r
         self.ConstPcd                  = {}\r
 \r
+\r
     def __repr__(self):\r
         return "%s [%s]" % (self.MetaFile, self.Arch)\r
 \r
     # Get FixedAtBuild Pcds of this Module\r
-    def _GetFixedAtBuildPcds(self):\r
-        if self._FixedAtBuildPcds:\r
-            return self._FixedAtBuildPcds\r
+    @cached_property\r
+    def FixedAtBuildPcds(self):\r
+        RetVal = []\r
         for Pcd in self.ModulePcdList:\r
             if Pcd.Type != TAB_PCDS_FIXED_AT_BUILD:\r
                 continue\r
-            if Pcd not in self._FixedAtBuildPcds:\r
-                self._FixedAtBuildPcds.append(Pcd)\r
-                \r
-        return self._FixedAtBuildPcds        \r
-\r
-    def _GetUniqueBaseName(self):\r
+            if Pcd not in RetVal:\r
+                RetVal.append(Pcd)\r
+        return RetVal\r
+\r
+    @cached_property\r
+    def FixedVoidTypePcds(self):\r
+        RetVal = {}\r
+        for Pcd in self.FixedAtBuildPcds:\r
+            if Pcd.DatumType == TAB_VOID:\r
+                if '{}.{}'.format(Pcd.TokenSpaceGuidCName, Pcd.TokenCName) not in RetVal:\r
+                    RetVal['{}.{}'.format(Pcd.TokenSpaceGuidCName, Pcd.TokenCName)] = Pcd.DefaultValue\r
+        return RetVal\r
+\r
+    @property\r
+    def UniqueBaseName(self):\r
         BaseName = self.Name\r
         for Module in self.PlatformInfo.ModuleAutoGenList:\r
             if Module.MetaFile == self.MetaFile:\r
@@ -2774,65 +2608,60 @@ class ModuleAutoGen(AutoGen):
         return BaseName\r
 \r
     # Macros could be used in build_rule.txt (also Makefile)\r
-    def _GetMacros(self):\r
-        if self._Macro is None:\r
-            self._Macro = OrderedDict()\r
-            self._Macro["WORKSPACE"             ] = self.WorkspaceDir\r
-            self._Macro["MODULE_NAME"           ] = self.Name\r
-            self._Macro["MODULE_NAME_GUID"      ] = self._GetUniqueBaseName()\r
-            self._Macro["MODULE_GUID"           ] = self.Guid\r
-            self._Macro["MODULE_VERSION"        ] = self.Version\r
-            self._Macro["MODULE_TYPE"           ] = self.ModuleType\r
-            self._Macro["MODULE_FILE"           ] = str(self.MetaFile)\r
-            self._Macro["MODULE_FILE_BASE_NAME" ] = self.MetaFile.BaseName\r
-            self._Macro["MODULE_RELATIVE_DIR"   ] = self.SourceDir\r
-            self._Macro["MODULE_DIR"            ] = self.SourceDir\r
-\r
-            self._Macro["BASE_NAME"             ] = self.Name\r
-\r
-            self._Macro["ARCH"                  ] = self.Arch\r
-            self._Macro["TOOLCHAIN"             ] = self.ToolChain\r
-            self._Macro["TOOLCHAIN_TAG"         ] = self.ToolChain\r
-            self._Macro["TOOL_CHAIN_TAG"        ] = self.ToolChain\r
-            self._Macro["TARGET"                ] = self.BuildTarget\r
-\r
-            self._Macro["BUILD_DIR"             ] = self.PlatformInfo.BuildDir\r
-            self._Macro["BIN_DIR"               ] = os.path.join(self.PlatformInfo.BuildDir, self.Arch)\r
-            self._Macro["LIB_DIR"               ] = os.path.join(self.PlatformInfo.BuildDir, self.Arch)\r
-            self._Macro["MODULE_BUILD_DIR"      ] = self.BuildDir\r
-            self._Macro["OUTPUT_DIR"            ] = self.OutputDir\r
-            self._Macro["DEBUG_DIR"             ] = self.DebugDir\r
-            self._Macro["DEST_DIR_OUTPUT"       ] = self.OutputDir\r
-            self._Macro["DEST_DIR_DEBUG"        ] = self.DebugDir\r
-            self._Macro["PLATFORM_NAME"         ] = self.PlatformInfo.Name\r
-            self._Macro["PLATFORM_GUID"         ] = self.PlatformInfo.Guid\r
-            self._Macro["PLATFORM_VERSION"      ] = self.PlatformInfo.Version\r
-            self._Macro["PLATFORM_RELATIVE_DIR" ] = self.PlatformInfo.SourceDir\r
-            self._Macro["PLATFORM_DIR"          ] = mws.join(self.WorkspaceDir, self.PlatformInfo.SourceDir)\r
-            self._Macro["PLATFORM_OUTPUT_DIR"   ] = self.PlatformInfo.OutputDir\r
-            self._Macro["FFS_OUTPUT_DIR"        ] = self.FfsOutputDir\r
-        return self._Macro\r
+    @cached_property\r
+    def Macros(self):\r
+        return OrderedDict((\r
+            ("WORKSPACE" ,self.WorkspaceDir),\r
+            ("MODULE_NAME" ,self.Name),\r
+            ("MODULE_NAME_GUID" ,self.UniqueBaseName),\r
+            ("MODULE_GUID" ,self.Guid),\r
+            ("MODULE_VERSION" ,self.Version),\r
+            ("MODULE_TYPE" ,self.ModuleType),\r
+            ("MODULE_FILE" ,str(self.MetaFile)),\r
+            ("MODULE_FILE_BASE_NAME" ,self.MetaFile.BaseName),\r
+            ("MODULE_RELATIVE_DIR" ,self.SourceDir),\r
+            ("MODULE_DIR" ,self.SourceDir),\r
+            ("BASE_NAME" ,self.Name),\r
+            ("ARCH" ,self.Arch),\r
+            ("TOOLCHAIN" ,self.ToolChain),\r
+            ("TOOLCHAIN_TAG" ,self.ToolChain),\r
+            ("TOOL_CHAIN_TAG" ,self.ToolChain),\r
+            ("TARGET" ,self.BuildTarget),\r
+            ("BUILD_DIR" ,self.PlatformInfo.BuildDir),\r
+            ("BIN_DIR" ,os.path.join(self.PlatformInfo.BuildDir, self.Arch)),\r
+            ("LIB_DIR" ,os.path.join(self.PlatformInfo.BuildDir, self.Arch)),\r
+            ("MODULE_BUILD_DIR" ,self.BuildDir),\r
+            ("OUTPUT_DIR" ,self.OutputDir),\r
+            ("DEBUG_DIR" ,self.DebugDir),\r
+            ("DEST_DIR_OUTPUT" ,self.OutputDir),\r
+            ("DEST_DIR_DEBUG" ,self.DebugDir),\r
+            ("PLATFORM_NAME" ,self.PlatformInfo.Name),\r
+            ("PLATFORM_GUID" ,self.PlatformInfo.Guid),\r
+            ("PLATFORM_VERSION" ,self.PlatformInfo.Version),\r
+            ("PLATFORM_RELATIVE_DIR" ,self.PlatformInfo.SourceDir),\r
+            ("PLATFORM_DIR" ,mws.join(self.WorkspaceDir, self.PlatformInfo.SourceDir)),\r
+            ("PLATFORM_OUTPUT_DIR" ,self.PlatformInfo.OutputDir),\r
+            ("FFS_OUTPUT_DIR" ,self.FfsOutputDir)\r
+            ))\r
 \r
     ## Return the module build data object\r
-    def _GetModule(self):\r
-        if self._Module is None:\r
-            self._Module = self.Workspace.BuildDatabase[self.MetaFile, self.Arch, self.BuildTarget, self.ToolChain]\r
-        return self._Module\r
+    @cached_property\r
+    def Module(self):\r
+        return self.Workspace.BuildDatabase[self.MetaFile, self.Arch, self.BuildTarget, self.ToolChain]\r
 \r
     ## Return the module name\r
-    def _GetBaseName(self):\r
+    @cached_property\r
+    def Name(self):\r
         return self.Module.BaseName\r
 \r
     ## Return the module DxsFile if exist\r
-    def _GetDxsFile(self):\r
+    @cached_property\r
+    def DxsFile(self):\r
         return self.Module.DxsFile\r
 \r
-    ## Return the module SourceOverridePath\r
-    def _GetSourceOverridePath(self):\r
-        return self.Module.SourceOverridePath\r
-\r
     ## Return the module meta-file GUID\r
-    def _GetGuid(self):\r
+    @cached_property\r
+    def Guid(self):\r
         #\r
         # To build same module more than once, the module path with FILE_GUID overridden has\r
         # the file name FILE_GUIDmodule.inf, but the relative path (self.MetaFile.File) is the realy path\r
@@ -2846,111 +2675,109 @@ class ModuleAutoGen(AutoGen):
         return self.Module.Guid\r
 \r
     ## Return the module version\r
-    def _GetVersion(self):\r
+    @cached_property\r
+    def Version(self):\r
         return self.Module.Version\r
 \r
     ## Return the module type\r
-    def _GetModuleType(self):\r
+    @cached_property\r
+    def ModuleType(self):\r
         return self.Module.ModuleType\r
 \r
     ## Return the component type (for Edk.x style of module)\r
-    def _GetComponentType(self):\r
+    @cached_property\r
+    def ComponentType(self):\r
         return self.Module.ComponentType\r
 \r
     ## Return the build type\r
-    def _GetBuildType(self):\r
+    @cached_property\r
+    def BuildType(self):\r
         return self.Module.BuildType\r
 \r
     ## Return the PCD_IS_DRIVER setting\r
-    def _GetPcdIsDriver(self):\r
+    @cached_property\r
+    def PcdIsDriver(self):\r
         return self.Module.PcdIsDriver\r
 \r
     ## Return the autogen version, i.e. module meta-file version\r
-    def _GetAutoGenVersion(self):\r
+    @cached_property\r
+    def AutoGenVersion(self):\r
         return self.Module.AutoGenVersion\r
 \r
     ## Check if the module is library or not\r
-    def _IsLibrary(self):\r
-        if self._LibraryFlag is None:\r
-            self._LibraryFlag = True if self.Module.LibraryClass else False\r
-        return self._LibraryFlag\r
+    @cached_property\r
+    def IsLibrary(self):\r
+        return bool(self.Module.LibraryClass)\r
 \r
     ## Check if the module is binary module or not\r
-    def _IsBinaryModule(self):\r
+    @cached_property\r
+    def IsBinaryModule(self):\r
         return self.Module.IsBinaryModule\r
 \r
     ## Return the directory to store intermediate files of the module\r
-    def _GetBuildDir(self):\r
-        if self._BuildDir is None:\r
-            self._BuildDir = path.join(\r
+    @cached_property\r
+    def BuildDir(self):\r
+        return _MakeDir((\r
                                     self.PlatformInfo.BuildDir,\r
                                     self.Arch,\r
                                     self.SourceDir,\r
                                     self.MetaFile.BaseName\r
-                                    )\r
-            CreateDirectory(self._BuildDir)\r
-        return self._BuildDir\r
+            ))\r
 \r
     ## Return the directory to store the intermediate object files of the mdoule\r
-    def _GetOutputDir(self):\r
-        if self._OutputDir is None:\r
-            self._OutputDir = path.join(self.BuildDir, "OUTPUT")\r
-            CreateDirectory(self._OutputDir)\r
-        return self._OutputDir\r
-\r
-    ## Return the directory to store ffs file\r
-    def _GetFfsOutputDir(self):\r
-        if self._FfsOutputDir is None:\r
-            if GlobalData.gFdfParser is not None:\r
-                self._FfsOutputDir = path.join(self.PlatformInfo.BuildDir, TAB_FV_DIRECTORY, "Ffs", self.Guid + self.Name)\r
-            else:\r
-                self._FfsOutputDir = ''\r
-        return self._FfsOutputDir\r
+    @cached_property\r
+    def OutputDir(self):\r
+        return _MakeDir((self.BuildDir, "OUTPUT"))\r
+\r
+    ## Return the directory path to store ffs file\r
+    @cached_property\r
+    def FfsOutputDir(self):\r
+        if GlobalData.gFdfParser:\r
+            return path.join(self.PlatformInfo.BuildDir, TAB_FV_DIRECTORY, "Ffs", self.Guid + self.Name)\r
+        return ''\r
 \r
     ## Return the directory to store auto-gened source files of the mdoule\r
-    def _GetDebugDir(self):\r
-        if self._DebugDir is None:\r
-            self._DebugDir = path.join(self.BuildDir, "DEBUG")\r
-            CreateDirectory(self._DebugDir)\r
-        return self._DebugDir\r
+    @cached_property\r
+    def DebugDir(self):\r
+        return _MakeDir((self.BuildDir, "DEBUG"))\r
 \r
     ## Return the path of custom file\r
-    def _GetCustomMakefile(self):\r
-        if self._CustomMakefile is None:\r
-            self._CustomMakefile = {}\r
-            for Type in self.Module.CustomMakefile:\r
-                if Type in gMakeTypeMap:\r
-                    MakeType = gMakeTypeMap[Type]\r
-                else:\r
-                    MakeType = 'nmake'\r
-                if self.SourceOverrideDir is not None:\r
-                    File = os.path.join(self.SourceOverrideDir, self.Module.CustomMakefile[Type])\r
-                    if not os.path.exists(File):\r
-                        File = os.path.join(self.SourceDir, self.Module.CustomMakefile[Type])\r
-                else:\r
+    @cached_property\r
+    def CustomMakefile(self):\r
+        RetVal = {}\r
+        for Type in self.Module.CustomMakefile:\r
+            MakeType = gMakeTypeMap[Type] if Type in gMakeTypeMap else 'nmake'\r
+            if self.SourceOverrideDir is not None:\r
+                File = os.path.join(self.SourceOverrideDir, self.Module.CustomMakefile[Type])\r
+                if not os.path.exists(File):\r
                     File = os.path.join(self.SourceDir, self.Module.CustomMakefile[Type])\r
-                self._CustomMakefile[MakeType] = File\r
-        return self._CustomMakefile\r
+            else:\r
+                File = os.path.join(self.SourceDir, self.Module.CustomMakefile[Type])\r
+            RetVal[MakeType] = File\r
+        return RetVal\r
 \r
     ## Return the directory of the makefile\r
     #\r
     #   @retval     string  The directory string of module's makefile\r
     #\r
-    def _GetMakeFileDir(self):\r
+    @cached_property\r
+    def MakeFileDir(self):\r
         return self.BuildDir\r
 \r
     ## Return build command string\r
     #\r
     #   @retval     string  Build command string\r
     #\r
-    def _GetBuildCommand(self):\r
+    @cached_property\r
+    def BuildCommand(self):\r
         return self.PlatformInfo.BuildCommand\r
 \r
     ## Get object list of all packages the module and its dependent libraries belong to\r
     #\r
     #   @retval     list    The list of package object\r
     #\r
-    def _GetDerivedPackageList(self):\r
+    @cached_property\r
+    def DerivedPackageList(self):\r
         PackageList = []\r
         for M in [self.Module] + self.DependentLibraryList:\r
             for Package in M.Packages:\r
@@ -2958,7 +2785,7 @@ class ModuleAutoGen(AutoGen):
                     continue\r
                 PackageList.append(Package)\r
         return PackageList\r
-    \r
+\r
     ## Get the depex string\r
     #\r
     # @return : a string contain all depex expresion.\r
@@ -2987,7 +2814,7 @@ class ModuleAutoGen(AutoGen):
                           (Arch.upper() == self.Arch.upper() and \\r
                           ModuleType.upper() in [TAB_ARCH_COMMON, self.ModuleType.upper()]):\r
                             DepexList.append({(Arch, ModuleType): DepexExpr})\r
-        \r
+\r
         #the type of build module is USER_DEFINED.\r
         if self.ModuleType.upper() == SUP_MODULE_USER_DEFINED:\r
             for Depex in DepexList:\r
@@ -2998,7 +2825,7 @@ class ModuleAutoGen(AutoGen):
             if not DepexStr:\r
                 return '[Depex.%s]\n' % self.Arch\r
             return DepexStr\r
-        \r
+\r
         #the type of build module not is USER_DEFINED.\r
         Count = 0\r
         for Depex in DepexList:\r
@@ -3018,78 +2845,84 @@ class ModuleAutoGen(AutoGen):
         if not DepexStr:\r
             return '[Depex.%s]\n' % self.Arch\r
         return '[Depex.%s]\n#  ' % self.Arch + DepexStr\r
-    \r
+\r
     ## Merge dependency expression\r
     #\r
     #   @retval     list    The token list of the dependency expression after parsed\r
     #\r
-    def _GetDepexTokenList(self):\r
-        if self._DepexDict is None:\r
-            self._DepexDict = {}\r
-            if self.DxsFile or self.IsLibrary or TAB_DEPENDENCY_EXPRESSION_FILE in self.FileTypes:\r
-                return self._DepexDict\r
-\r
-            self._DepexDict[self.ModuleType] = []\r
+    @cached_property\r
+    def DepexList(self):\r
+        if self.DxsFile or self.IsLibrary or TAB_DEPENDENCY_EXPRESSION_FILE in self.FileTypes:\r
+            return {}\r
 \r
-            for ModuleType in self._DepexDict:\r
-                DepexList = self._DepexDict[ModuleType]\r
-                #\r
-                # Append depex from dependent libraries, if not "BEFORE", "AFTER" expresion\r
-                #\r
-                for M in [self.Module] + self.DependentLibraryList:\r
-                    Inherited = False\r
-                    for D in M.Depex[self.Arch, ModuleType]:\r
-                        if DepexList != []:\r
-                            DepexList.append('AND')\r
-                        DepexList.append('(')\r
-                        DepexList.extend(D)\r
-                        if DepexList[-1] == 'END':  # no need of a END at this time\r
-                            DepexList.pop()\r
-                        DepexList.append(')')\r
-                        Inherited = True\r
-                    if Inherited:\r
-                        EdkLogger.verbose("DEPEX[%s] (+%s) = %s" % (self.Name, M.BaseName, DepexList))\r
-                    if 'BEFORE' in DepexList or 'AFTER' in DepexList:\r
-                        break\r
-                if len(DepexList) > 0:\r
-                    EdkLogger.verbose('')\r
-        return self._DepexDict\r
+        DepexList = []\r
+        #\r
+        # Append depex from dependent libraries, if not "BEFORE", "AFTER" expresion\r
+        #\r
+        for M in [self.Module] + self.DependentLibraryList:\r
+            Inherited = False\r
+            for D in M.Depex[self.Arch, self.ModuleType]:\r
+                if DepexList != []:\r
+                    DepexList.append('AND')\r
+                DepexList.append('(')\r
+                #replace D with value if D is FixedAtBuild PCD\r
+                NewList = []\r
+                for item in D:\r
+                    if '.' not in item:\r
+                        NewList.append(item)\r
+                    else:\r
+                        if item not in self._FixedPcdVoidTypeDict:\r
+                            EdkLogger.error("build", FORMAT_INVALID, "{} used in [Depex] section should be used as FixedAtBuild type and VOID* datum type in the module.".format(item))\r
+                        else:\r
+                            Value = self._FixedPcdVoidTypeDict[item]\r
+                            if len(Value.split(',')) != 16:\r
+                                EdkLogger.error("build", FORMAT_INVALID,\r
+                                                "{} used in [Depex] section should be used as FixedAtBuild type and VOID* datum type and 16 bytes in the module.".format(item))\r
+                            NewList.append(Value)\r
+                DepexList.extend(NewList)\r
+                if DepexList[-1] == 'END':  # no need of a END at this time\r
+                    DepexList.pop()\r
+                DepexList.append(')')\r
+                Inherited = True\r
+            if Inherited:\r
+                EdkLogger.verbose("DEPEX[%s] (+%s) = %s" % (self.Name, M.BaseName, DepexList))\r
+            if 'BEFORE' in DepexList or 'AFTER' in DepexList:\r
+                break\r
+            if len(DepexList) > 0:\r
+                EdkLogger.verbose('')\r
+        return {self.ModuleType:DepexList}\r
 \r
     ## Merge dependency expression\r
     #\r
     #   @retval     list    The token list of the dependency expression after parsed\r
     #\r
-    def _GetDepexExpressionTokenList(self):\r
-        if self._DepexExpressionDict is None:\r
-            self._DepexExpressionDict = {}\r
-            if self.DxsFile or self.IsLibrary or TAB_DEPENDENCY_EXPRESSION_FILE in self.FileTypes:\r
-                return self._DepexExpressionDict\r
+    @cached_property\r
+    def DepexExpressionDict(self):\r
+        if self.DxsFile or self.IsLibrary or TAB_DEPENDENCY_EXPRESSION_FILE in self.FileTypes:\r
+            return {}\r
 \r
-            self._DepexExpressionDict[self.ModuleType] = ''\r
+        DepexExpressionString = ''\r
+        #\r
+        # Append depex from dependent libraries, if not "BEFORE", "AFTER" expresion\r
+        #\r
+        for M in [self.Module] + self.DependentLibraryList:\r
+            Inherited = False\r
+            for D in M.DepexExpression[self.Arch, self.ModuleType]:\r
+                if DepexExpressionString != '':\r
+                    DepexExpressionString += ' AND '\r
+                DepexExpressionString += '('\r
+                DepexExpressionString += D\r
+                DepexExpressionString = DepexExpressionString.rstrip('END').strip()\r
+                DepexExpressionString += ')'\r
+                Inherited = True\r
+            if Inherited:\r
+                EdkLogger.verbose("DEPEX[%s] (+%s) = %s" % (self.Name, M.BaseName, DepexExpressionString))\r
+            if 'BEFORE' in DepexExpressionString or 'AFTER' in DepexExpressionString:\r
+                break\r
+        if len(DepexExpressionString) > 0:\r
+            EdkLogger.verbose('')\r
 \r
-            for ModuleType in self._DepexExpressionDict:\r
-                DepexExpressionString = self._DepexExpressionDict[ModuleType]\r
-                #\r
-                # Append depex from dependent libraries, if not "BEFORE", "AFTER" expresion\r
-                #\r
-                for M in [self.Module] + self.DependentLibraryList:\r
-                    Inherited = False\r
-                    for D in M.DepexExpression[self.Arch, ModuleType]:\r
-                        if DepexExpressionString != '':\r
-                            DepexExpressionString += ' AND '\r
-                        DepexExpressionString += '('\r
-                        DepexExpressionString += D\r
-                        DepexExpressionString = DepexExpressionString.rstrip('END').strip()\r
-                        DepexExpressionString += ')'\r
-                        Inherited = True\r
-                    if Inherited:\r
-                        EdkLogger.verbose("DEPEX[%s] (+%s) = %s" % (self.Name, M.BaseName, DepexExpressionString))\r
-                    if 'BEFORE' in DepexExpressionString or 'AFTER' in DepexExpressionString:\r
-                        break\r
-                if len(DepexExpressionString) > 0:\r
-                    EdkLogger.verbose('')\r
-                self._DepexExpressionDict[ModuleType] = DepexExpressionString\r
-        return self._DepexExpressionDict\r
+        return {self.ModuleType:DepexExpressionString}\r
 \r
     # Get the tiano core user extension, it is contain dependent library.\r
     # @retval: a list contain tiano core userextension.\r
@@ -3119,7 +2952,8 @@ class ModuleAutoGen(AutoGen):
     #\r
     #   @retval     list    The list of specification defined in module file\r
     #\r
-    def _GetSpecification(self):\r
+    @cached_property\r
+    def Specification(self):\r
         return self.Module.Specification\r
 \r
     ## Tool option for the module build\r
@@ -3127,109 +2961,105 @@ class ModuleAutoGen(AutoGen):
     #   @param      PlatformInfo    The object of PlatformBuildInfo\r
     #   @retval     dict            The dict containing valid options\r
     #\r
-    def _GetModuleBuildOption(self):\r
-        if self._BuildOption is None:\r
-            self._BuildOption, self.BuildRuleOrder = self.PlatformInfo.ApplyBuildOption(self.Module)\r
-            if self.BuildRuleOrder:\r
-                self.BuildRuleOrder = ['.%s' % Ext for Ext in self.BuildRuleOrder.split()]\r
-        return self._BuildOption\r
+    @cached_property\r
+    def BuildOption(self):\r
+        RetVal, self.BuildRuleOrder = self.PlatformInfo.ApplyBuildOption(self.Module)\r
+        if self.BuildRuleOrder:\r
+            self.BuildRuleOrder = ['.%s' % Ext for Ext in self.BuildRuleOrder.split()]\r
+        return RetVal\r
 \r
     ## Get include path list from tool option for the module build\r
     #\r
     #   @retval     list            The include path list\r
     #\r
-    def _GetBuildOptionIncPathList(self):\r
-        if self._BuildOptionIncPathList is None:\r
+    @cached_property\r
+    def BuildOptionIncPathList(self):\r
+        #\r
+        # Regular expression for finding Include Directories, the difference between MSFT and INTEL/GCC/RVCT\r
+        # is the former use /I , the Latter used -I to specify include directories\r
+        #\r
+        if self.PlatformInfo.ToolChainFamily in (TAB_COMPILER_MSFT):\r
+            BuildOptIncludeRegEx = gBuildOptIncludePatternMsft\r
+        elif self.PlatformInfo.ToolChainFamily in ('INTEL', 'GCC', 'RVCT'):\r
+            BuildOptIncludeRegEx = gBuildOptIncludePatternOther\r
+        else:\r
             #\r
-            # Regular expression for finding Include Directories, the difference between MSFT and INTEL/GCC/RVCT\r
-            # is the former use /I , the Latter used -I to specify include directories\r
+            # New ToolChainFamily, don't known whether there is option to specify include directories\r
             #\r
-            if self.PlatformInfo.ToolChainFamily in ('MSFT'):\r
-                BuildOptIncludeRegEx = gBuildOptIncludePatternMsft\r
-            elif self.PlatformInfo.ToolChainFamily in ('INTEL', 'GCC', 'RVCT'):\r
-                BuildOptIncludeRegEx = gBuildOptIncludePatternOther\r
+            return []\r
+\r
+        RetVal = []\r
+        for Tool in ('CC', 'PP', 'VFRPP', 'ASLPP', 'ASLCC', 'APP', 'ASM'):\r
+            try:\r
+                FlagOption = self.BuildOption[Tool]['FLAGS']\r
+            except KeyError:\r
+                FlagOption = ''\r
+\r
+            if self.PlatformInfo.ToolChainFamily != 'RVCT':\r
+                IncPathList = [NormPath(Path, self.Macros) for Path in BuildOptIncludeRegEx.findall(FlagOption)]\r
             else:\r
                 #\r
-                # New ToolChainFamily, don't known whether there is option to specify include directories\r
+                # RVCT may specify a list of directory seperated by commas\r
                 #\r
-                self._BuildOptionIncPathList = []\r
-                return self._BuildOptionIncPathList\r
-            \r
-            BuildOptionIncPathList = []\r
-            for Tool in ('CC', 'PP', 'VFRPP', 'ASLPP', 'ASLCC', 'APP', 'ASM'):\r
-                try:\r
-                    FlagOption = self.BuildOption[Tool]['FLAGS']\r
-                except KeyError:\r
-                    FlagOption = ''\r
-                \r
-                if self.PlatformInfo.ToolChainFamily != 'RVCT':\r
-                    IncPathList = [NormPath(Path, self.Macros) for Path in BuildOptIncludeRegEx.findall(FlagOption)]\r
-                else:\r
-                    #\r
-                    # RVCT may specify a list of directory seperated by commas\r
-                    #\r
-                    IncPathList = []\r
-                    for Path in BuildOptIncludeRegEx.findall(FlagOption):\r
-                        PathList = GetSplitList(Path, TAB_COMMA_SPLIT)\r
-                        IncPathList.extend(NormPath(PathEntry, self.Macros) for PathEntry in PathList)\r
+                IncPathList = []\r
+                for Path in BuildOptIncludeRegEx.findall(FlagOption):\r
+                    PathList = GetSplitList(Path, TAB_COMMA_SPLIT)\r
+                    IncPathList.extend(NormPath(PathEntry, self.Macros) for PathEntry in PathList)\r
+\r
+            #\r
+            # EDK II modules must not reference header files outside of the packages they depend on or\r
+            # within the module's directory tree. Report error if violation.\r
+            #\r
+            if self.AutoGenVersion >= 0x00010005:\r
+                for Path in IncPathList:\r
+                    if (Path not in self.IncludePathList) and (CommonPath([Path, self.MetaFile.Dir]) != self.MetaFile.Dir):\r
+                        ErrMsg = "The include directory for the EDK II module in this line is invalid %s specified in %s FLAGS '%s'" % (Path, Tool, FlagOption)\r
+                        EdkLogger.error("build",\r
+                                        PARAMETER_INVALID,\r
+                                        ExtraData=ErrMsg,\r
+                                        File=str(self.MetaFile))\r
+            RetVal += IncPathList\r
+        return RetVal\r
 \r
-                #\r
-                # EDK II modules must not reference header files outside of the packages they depend on or \r
-                # within the module's directory tree. Report error if violation.\r
-                #\r
-                if self.AutoGenVersion >= 0x00010005:\r
-                    for Path in IncPathList:\r
-                        if (Path not in self.IncludePathList) and (CommonPath([Path, self.MetaFile.Dir]) != self.MetaFile.Dir):\r
-                            ErrMsg = "The include directory for the EDK II module in this line is invalid %s specified in %s FLAGS '%s'" % (Path, Tool, FlagOption)\r
-                            EdkLogger.error("build",\r
-                                            PARAMETER_INVALID,\r
-                                            ExtraData=ErrMsg,\r
-                                            File=str(self.MetaFile))\r
-\r
-                \r
-                BuildOptionIncPathList += IncPathList\r
-            \r
-            self._BuildOptionIncPathList = BuildOptionIncPathList\r
-        \r
-        return self._BuildOptionIncPathList\r
-        \r
     ## Return a list of files which can be built from source\r
     #\r
     #  What kind of files can be built is determined by build rules in\r
     #  $(CONF_DIRECTORY)/build_rule.txt and toolchain family.\r
     #\r
-    def _GetSourceFileList(self):\r
-        if self._SourceFileList is None:\r
-            self._SourceFileList = []\r
-            for F in self.Module.Sources:\r
-                # match tool chain\r
-                if F.TagName not in ("", "*", self.ToolChain):\r
-                    EdkLogger.debug(EdkLogger.DEBUG_9, "The toolchain [%s] for processing file [%s] is found, "\r
-                                    "but [%s] is needed" % (F.TagName, str(F), self.ToolChain))\r
-                    continue\r
-                # match tool chain family or build rule family\r
-                if F.ToolChainFamily not in ("", "*", self.ToolChainFamily, self.BuildRuleFamily):\r
-                    EdkLogger.debug(\r
-                                EdkLogger.DEBUG_0,\r
-                                "The file [%s] must be built by tools of [%s], " \\r
-                                "but current toolchain family is [%s], buildrule family is [%s]" \\r
-                                    % (str(F), F.ToolChainFamily, self.ToolChainFamily, self.BuildRuleFamily))\r
-                    continue\r
+    @cached_property\r
+    def SourceFileList(self):\r
+        RetVal = []\r
+        ToolChainTagSet = {"", "*", self.ToolChain}\r
+        ToolChainFamilySet = {"", "*", self.ToolChainFamily, self.BuildRuleFamily}\r
+        for F in self.Module.Sources:\r
+            # match tool chain\r
+            if F.TagName not in ToolChainTagSet:\r
+                EdkLogger.debug(EdkLogger.DEBUG_9, "The toolchain [%s] for processing file [%s] is found, "\r
+                                "but [%s] is currently used" % (F.TagName, str(F), self.ToolChain))\r
+                continue\r
+            # match tool chain family or build rule family\r
+            if F.ToolChainFamily not in ToolChainFamilySet:\r
+                EdkLogger.debug(\r
+                            EdkLogger.DEBUG_0,\r
+                            "The file [%s] must be built by tools of [%s], " \\r
+                            "but current toolchain family is [%s], buildrule family is [%s]" \\r
+                                % (str(F), F.ToolChainFamily, self.ToolChainFamily, self.BuildRuleFamily))\r
+                continue\r
 \r
-                # add the file path into search path list for file including\r
-                if F.Dir not in self.IncludePathList and self.AutoGenVersion >= 0x00010005:\r
-                    self.IncludePathList.insert(0, F.Dir)\r
-                self._SourceFileList.append(F)\r
+            # add the file path into search path list for file including\r
+            if F.Dir not in self.IncludePathList and self.AutoGenVersion >= 0x00010005:\r
+                self.IncludePathList.insert(0, F.Dir)\r
+            RetVal.append(F)\r
 \r
-            self._MatchBuildRuleOrder(self._SourceFileList)\r
+        self._MatchBuildRuleOrder(RetVal)\r
 \r
-            for F in self._SourceFileList:\r
-                self._ApplyBuildRule(F, TAB_UNKNOWN_FILE)\r
-        return self._SourceFileList\r
+        for F in RetVal:\r
+            self._ApplyBuildRule(F, TAB_UNKNOWN_FILE)\r
+        return RetVal\r
 \r
     def _MatchBuildRuleOrder(self, FileList):\r
         Order_Dict = {}\r
-        self._GetModuleBuildOption()\r
+        self.BuildOption\r
         for SingleFile in FileList:\r
             if self.BuildRuleOrder and SingleFile.Ext in self.BuildRuleOrder and SingleFile.Ext in self.BuildRules:\r
                 key = SingleFile.Path.split(SingleFile.Ext)[0]\r
@@ -3244,38 +3074,26 @@ class ModuleAutoGen(AutoGen):
                 Order_Dict[F].sort(key=lambda i: self.BuildRuleOrder.index(i))\r
                 for Ext in Order_Dict[F][1:]:\r
                     RemoveList.append(F + Ext)\r
-                   \r
+\r
         for item in RemoveList:\r
             FileList.remove(item)\r
 \r
         return FileList\r
 \r
     ## Return the list of unicode files\r
-    def _GetUnicodeFileList(self):\r
-        if self._UnicodeFileList is None:\r
-            if TAB_UNICODE_FILE in self.FileTypes:\r
-                self._UnicodeFileList = self.FileTypes[TAB_UNICODE_FILE]\r
-            else:\r
-                self._UnicodeFileList = []\r
-        return self._UnicodeFileList\r
+    @cached_property\r
+    def UnicodeFileList(self):\r
+        return self.FileTypes.get(TAB_UNICODE_FILE,[])\r
 \r
     ## Return the list of vfr files\r
-    def _GetVfrFileList(self):\r
-        if self._VfrFileList is None:\r
-            if TAB_VFR_FILE in self.FileTypes:\r
-                self._VfrFileList = self.FileTypes[TAB_VFR_FILE]\r
-            else:\r
-                self._VfrFileList = []\r
-        return self._VfrFileList\r
+    @cached_property\r
+    def VfrFileList(self):\r
+        return self.FileTypes.get(TAB_VFR_FILE, [])\r
 \r
     ## Return the list of Image Definition files\r
-    def _GetIdfFileList(self):\r
-        if self._IdfFileList is None:\r
-            if TAB_IMAGE_FILE in self.FileTypes:\r
-                self._IdfFileList = self.FileTypes[TAB_IMAGE_FILE]\r
-            else:\r
-                self._IdfFileList = []\r
-        return self._IdfFileList\r
+    @cached_property\r
+    def IdfFileList(self):\r
+        return self.FileTypes.get(TAB_IMAGE_FILE,[])\r
 \r
     ## Return a list of files which can be built from binary\r
     #\r
@@ -3283,50 +3101,52 @@ class ModuleAutoGen(AutoGen):
     #\r
     #   @retval     list            The list of files which can be built later\r
     #\r
-    def _GetBinaryFiles(self):\r
-        if self._BinaryFileList is None:\r
-            self._BinaryFileList = []\r
-            for F in self.Module.Binaries:\r
-                if F.Target not in [TAB_ARCH_COMMON, '*'] and F.Target != self.BuildTarget:\r
-                    continue\r
-                self._BinaryFileList.append(F)\r
-                self._ApplyBuildRule(F, F.Type)\r
-        return self._BinaryFileList\r
-\r
-    def _GetBuildRules(self):\r
-        if self._BuildRules is None:\r
-            BuildRules = {}\r
-            BuildRuleDatabase = self.PlatformInfo.BuildRule\r
-            for Type in BuildRuleDatabase.FileTypeList:\r
-                #first try getting build rule by BuildRuleFamily\r
-                RuleObject = BuildRuleDatabase[Type, self.BuildType, self.Arch, self.BuildRuleFamily]\r
+    @cached_property\r
+    def BinaryFileList(self):\r
+        RetVal = []\r
+        for F in self.Module.Binaries:\r
+            if F.Target not in [TAB_ARCH_COMMON, '*'] and F.Target != self.BuildTarget:\r
+                continue\r
+            RetVal.append(F)\r
+            self._ApplyBuildRule(F, F.Type, BinaryFileList=RetVal)\r
+        return RetVal\r
+\r
+    @cached_property\r
+    def BuildRules(self):\r
+        RetVal = {}\r
+        BuildRuleDatabase = self.PlatformInfo.BuildRule\r
+        for Type in BuildRuleDatabase.FileTypeList:\r
+            #first try getting build rule by BuildRuleFamily\r
+            RuleObject = BuildRuleDatabase[Type, self.BuildType, self.Arch, self.BuildRuleFamily]\r
+            if not RuleObject:\r
+                # build type is always module type, but ...\r
+                if self.ModuleType != self.BuildType:\r
+                    RuleObject = BuildRuleDatabase[Type, self.ModuleType, self.Arch, self.BuildRuleFamily]\r
+            #second try getting build rule by ToolChainFamily\r
+            if not RuleObject:\r
+                RuleObject = BuildRuleDatabase[Type, self.BuildType, self.Arch, self.ToolChainFamily]\r
                 if not RuleObject:\r
                     # build type is always module type, but ...\r
                     if self.ModuleType != self.BuildType:\r
-                        RuleObject = BuildRuleDatabase[Type, self.ModuleType, self.Arch, self.BuildRuleFamily]\r
-                #second try getting build rule by ToolChainFamily\r
-                if not RuleObject:\r
-                    RuleObject = BuildRuleDatabase[Type, self.BuildType, self.Arch, self.ToolChainFamily]\r
-                    if not RuleObject:\r
-                        # build type is always module type, but ...\r
-                        if self.ModuleType != self.BuildType:\r
-                            RuleObject = BuildRuleDatabase[Type, self.ModuleType, self.Arch, self.ToolChainFamily]\r
-                if not RuleObject:\r
-                    continue\r
-                RuleObject = RuleObject.Instantiate(self.Macros)\r
-                BuildRules[Type] = RuleObject\r
-                for Ext in RuleObject.SourceFileExtList:\r
-                    BuildRules[Ext] = RuleObject\r
-            self._BuildRules = BuildRules\r
-        return self._BuildRules\r
-\r
-    def _ApplyBuildRule(self, File, FileType):\r
+                        RuleObject = BuildRuleDatabase[Type, self.ModuleType, self.Arch, self.ToolChainFamily]\r
+            if not RuleObject:\r
+                continue\r
+            RuleObject = RuleObject.Instantiate(self.Macros)\r
+            RetVal[Type] = RuleObject\r
+            for Ext in RuleObject.SourceFileExtList:\r
+                RetVal[Ext] = RuleObject\r
+        return RetVal\r
+\r
+    def _ApplyBuildRule(self, File, FileType, BinaryFileList=None):\r
         if self._BuildTargets is None:\r
             self._IntroBuildTargetList = set()\r
             self._FinalBuildTargetList = set()\r
             self._BuildTargets = defaultdict(set)\r
             self._FileTypes = defaultdict(set)\r
 \r
+        if not BinaryFileList:\r
+            BinaryFileList = self.BinaryFileList\r
+\r
         SubDirectory = os.path.join(self.OutputDir, File.SubDir)\r
         if not os.path.exists(SubDirectory):\r
             CreateDirectory(SubDirectory)\r
@@ -3337,7 +3157,7 @@ class ModuleAutoGen(AutoGen):
         #\r
         # Make sure to get build rule order value\r
         #\r
-        self._GetModuleBuildOption()\r
+        self.BuildOption\r
 \r
         while Index < len(SourceList):\r
             Source = SourceList[Index]\r
@@ -3346,7 +3166,7 @@ class ModuleAutoGen(AutoGen):
             if Source != File:\r
                 CreateDirectory(Source.Dir)\r
 \r
-            if File.IsBinary and File == Source and self._BinaryFileList is not None and File in self._BinaryFileList:\r
+            if File.IsBinary and File == Source and File in BinaryFileList:\r
                 # Skip all files that are not binary libraries\r
                 if not self.IsLibrary:\r
                     continue\r
@@ -3393,230 +3213,222 @@ class ModuleAutoGen(AutoGen):
             LastTarget = Target\r
             FileType = TAB_UNKNOWN_FILE\r
 \r
-    def _GetTargets(self):\r
+    @cached_property\r
+    def Targets(self):\r
         if self._BuildTargets is None:\r
             self._IntroBuildTargetList = set()\r
             self._FinalBuildTargetList = set()\r
             self._BuildTargets = defaultdict(set)\r
             self._FileTypes = defaultdict(set)\r
 \r
-        #TRICK: call _GetSourceFileList to apply build rule for source files\r
-        if self.SourceFileList:\r
-            pass\r
+        #TRICK: call SourceFileList property to apply build rule for source files\r
+        self.SourceFileList\r
 \r
         #TRICK: call _GetBinaryFileList to apply build rule for binary files\r
-        if self.BinaryFileList:\r
-            pass\r
+        self.BinaryFileList\r
 \r
         return self._BuildTargets\r
 \r
-    def _GetIntroTargetList(self):\r
-        self._GetTargets()\r
+    @cached_property\r
+    def IntroTargetList(self):\r
+        self.Targets\r
         return self._IntroBuildTargetList\r
 \r
-    def _GetFinalTargetList(self):\r
-        self._GetTargets()\r
+    @cached_property\r
+    def CodaTargetList(self):\r
+        self.Targets\r
         return self._FinalBuildTargetList\r
 \r
-    def _GetFileTypes(self):\r
-        self._GetTargets()\r
+    @cached_property\r
+    def FileTypes(self):\r
+        self.Targets\r
         return self._FileTypes\r
 \r
     ## Get the list of package object the module depends on\r
     #\r
     #   @retval     list    The package object list\r
     #\r
-    def _GetDependentPackageList(self):\r
+    @cached_property\r
+    def DependentPackageList(self):\r
         return self.Module.Packages\r
 \r
     ## Return the list of auto-generated code file\r
     #\r
     #   @retval     list        The list of auto-generated file\r
     #\r
-    def _GetAutoGenFileList(self):\r
-        UniStringAutoGenC = True\r
-        IdfStringAutoGenC = True\r
-        UniStringBinBuffer = StringIO()\r
-        IdfGenBinBuffer = StringIO()\r
-        if self.BuildType == 'UEFI_HII':\r
-            UniStringAutoGenC = False\r
-            IdfStringAutoGenC = False\r
-        if self._AutoGenFileList is None:\r
-            self._AutoGenFileList = {}\r
-            AutoGenC = TemplateString()\r
-            AutoGenH = TemplateString()\r
-            StringH = TemplateString()\r
-            StringIdf = TemplateString()\r
-            GenC.CreateCode(self, AutoGenC, AutoGenH, StringH, UniStringAutoGenC, UniStringBinBuffer, StringIdf, IdfStringAutoGenC, IdfGenBinBuffer)\r
-            #\r
-            # AutoGen.c is generated if there are library classes in inf, or there are object files\r
-            #\r
-            if str(AutoGenC) != "" and (len(self.Module.LibraryClasses) > 0\r
-                                        or TAB_OBJECT_FILE in self.FileTypes):\r
-                AutoFile = PathClass(gAutoGenCodeFileName, self.DebugDir)\r
-                self._AutoGenFileList[AutoFile] = str(AutoGenC)\r
-                self._ApplyBuildRule(AutoFile, TAB_UNKNOWN_FILE)\r
-            if str(AutoGenH) != "":\r
-                AutoFile = PathClass(gAutoGenHeaderFileName, self.DebugDir)\r
-                self._AutoGenFileList[AutoFile] = str(AutoGenH)\r
-                self._ApplyBuildRule(AutoFile, TAB_UNKNOWN_FILE)\r
-            if str(StringH) != "":\r
-                AutoFile = PathClass(gAutoGenStringFileName % {"module_name":self.Name}, self.DebugDir)\r
-                self._AutoGenFileList[AutoFile] = str(StringH)\r
-                self._ApplyBuildRule(AutoFile, TAB_UNKNOWN_FILE)\r
-            if UniStringBinBuffer is not None and UniStringBinBuffer.getvalue() != "":\r
-                AutoFile = PathClass(gAutoGenStringFormFileName % {"module_name":self.Name}, self.OutputDir)\r
-                self._AutoGenFileList[AutoFile] = UniStringBinBuffer.getvalue()\r
-                AutoFile.IsBinary = True\r
-                self._ApplyBuildRule(AutoFile, TAB_UNKNOWN_FILE)\r
-            if UniStringBinBuffer is not None:\r
-                UniStringBinBuffer.close()\r
-            if str(StringIdf) != "":\r
-                AutoFile = PathClass(gAutoGenImageDefFileName % {"module_name":self.Name}, self.DebugDir)\r
-                self._AutoGenFileList[AutoFile] = str(StringIdf)\r
-                self._ApplyBuildRule(AutoFile, TAB_UNKNOWN_FILE)\r
-            if IdfGenBinBuffer is not None and IdfGenBinBuffer.getvalue() != "":\r
-                AutoFile = PathClass(gAutoGenIdfFileName % {"module_name":self.Name}, self.OutputDir)\r
-                self._AutoGenFileList[AutoFile] = IdfGenBinBuffer.getvalue()\r
-                AutoFile.IsBinary = True\r
-                self._ApplyBuildRule(AutoFile, TAB_UNKNOWN_FILE)\r
-            if IdfGenBinBuffer is not None:\r
-                IdfGenBinBuffer.close()\r
-        return self._AutoGenFileList\r
+    @cached_property\r
+    def AutoGenFileList(self):\r
+        AutoGenUniIdf = self.BuildType != 'UEFI_HII'\r
+        UniStringBinBuffer = BytesIO()\r
+        IdfGenBinBuffer = BytesIO()\r
+        RetVal = {}\r
+        AutoGenC = TemplateString()\r
+        AutoGenH = TemplateString()\r
+        StringH = TemplateString()\r
+        StringIdf = TemplateString()\r
+        GenC.CreateCode(self, AutoGenC, AutoGenH, StringH, AutoGenUniIdf, UniStringBinBuffer, StringIdf, AutoGenUniIdf, IdfGenBinBuffer)\r
+        #\r
+        # AutoGen.c is generated if there are library classes in inf, or there are object files\r
+        #\r
+        if str(AutoGenC) != "" and (len(self.Module.LibraryClasses) > 0\r
+                                    or TAB_OBJECT_FILE in self.FileTypes):\r
+            AutoFile = PathClass(gAutoGenCodeFileName, self.DebugDir)\r
+            RetVal[AutoFile] = str(AutoGenC)\r
+            self._ApplyBuildRule(AutoFile, TAB_UNKNOWN_FILE)\r
+        if str(AutoGenH) != "":\r
+            AutoFile = PathClass(gAutoGenHeaderFileName, self.DebugDir)\r
+            RetVal[AutoFile] = str(AutoGenH)\r
+            self._ApplyBuildRule(AutoFile, TAB_UNKNOWN_FILE)\r
+        if str(StringH) != "":\r
+            AutoFile = PathClass(gAutoGenStringFileName % {"module_name":self.Name}, self.DebugDir)\r
+            RetVal[AutoFile] = str(StringH)\r
+            self._ApplyBuildRule(AutoFile, TAB_UNKNOWN_FILE)\r
+        if UniStringBinBuffer is not None and UniStringBinBuffer.getvalue() != "":\r
+            AutoFile = PathClass(gAutoGenStringFormFileName % {"module_name":self.Name}, self.OutputDir)\r
+            RetVal[AutoFile] = UniStringBinBuffer.getvalue()\r
+            AutoFile.IsBinary = True\r
+            self._ApplyBuildRule(AutoFile, TAB_UNKNOWN_FILE)\r
+        if UniStringBinBuffer is not None:\r
+            UniStringBinBuffer.close()\r
+        if str(StringIdf) != "":\r
+            AutoFile = PathClass(gAutoGenImageDefFileName % {"module_name":self.Name}, self.DebugDir)\r
+            RetVal[AutoFile] = str(StringIdf)\r
+            self._ApplyBuildRule(AutoFile, TAB_UNKNOWN_FILE)\r
+        if IdfGenBinBuffer is not None and IdfGenBinBuffer.getvalue() != "":\r
+            AutoFile = PathClass(gAutoGenIdfFileName % {"module_name":self.Name}, self.OutputDir)\r
+            RetVal[AutoFile] = IdfGenBinBuffer.getvalue()\r
+            AutoFile.IsBinary = True\r
+            self._ApplyBuildRule(AutoFile, TAB_UNKNOWN_FILE)\r
+        if IdfGenBinBuffer is not None:\r
+            IdfGenBinBuffer.close()\r
+        return RetVal\r
 \r
     ## Return the list of library modules explicitly or implicityly used by this module\r
-    def _GetLibraryList(self):\r
-        if self._DependentLibraryList is None:\r
-            # only merge library classes and PCD for non-library module\r
-            if self.IsLibrary:\r
-                self._DependentLibraryList = []\r
-            else:\r
-                if self.AutoGenVersion < 0x00010005:\r
-                    self._DependentLibraryList = self.PlatformInfo.ResolveLibraryReference(self.Module)\r
-                else:\r
-                    self._DependentLibraryList = self.PlatformInfo.ApplyLibraryInstance(self.Module)\r
-        return self._DependentLibraryList\r
+    @cached_property\r
+    def DependentLibraryList(self):\r
+        # only merge library classes and PCD for non-library module\r
+        if self.IsLibrary:\r
+            return []\r
+        if self.AutoGenVersion < 0x00010005:\r
+            return self.PlatformInfo.ResolveLibraryReference(self.Module)\r
+        return self.PlatformInfo.ApplyLibraryInstance(self.Module)\r
 \r
     ## Get the list of PCDs from current module\r
     #\r
     #   @retval     list                    The list of PCD\r
     #\r
-    def _GetModulePcdList(self):\r
-        if self._ModulePcdList is None:\r
-            # apply PCD settings from platform\r
-            self._ModulePcdList = self.PlatformInfo.ApplyPcdSetting(self.Module, self.Module.Pcds)\r
-            ExtendCopyDictionaryLists(self._PcdComments, self.Module.PcdComments)\r
-        return self._ModulePcdList\r
+    @cached_property\r
+    def ModulePcdList(self):\r
+        # apply PCD settings from platform\r
+        RetVal = self.PlatformInfo.ApplyPcdSetting(self.Module, self.Module.Pcds)\r
+        ExtendCopyDictionaryLists(self._PcdComments, self.Module.PcdComments)\r
+        return RetVal\r
 \r
     ## Get the list of PCDs from dependent libraries\r
     #\r
     #   @retval     list                    The list of PCD\r
     #\r
-    def _GetLibraryPcdList(self):\r
-        if self._LibraryPcdList is None:\r
-            Pcds = OrderedDict()\r
-            if not self.IsLibrary:\r
-                # get PCDs from dependent libraries\r
-                self._LibraryPcdList = []\r
-                for Library in self.DependentLibraryList:\r
-                    PcdsInLibrary = OrderedDict()\r
-                    ExtendCopyDictionaryLists(self._PcdComments, Library.PcdComments)\r
-                    for Key in Library.Pcds:\r
-                        # skip duplicated PCDs\r
-                        if Key in self.Module.Pcds or Key in Pcds:\r
-                            continue\r
-                        Pcds[Key] = copy.copy(Library.Pcds[Key])\r
-                        PcdsInLibrary[Key] = Pcds[Key]\r
-                    self._LibraryPcdList.extend(self.PlatformInfo.ApplyPcdSetting(self.Module, PcdsInLibrary, Library=Library))\r
-            else:\r
-                self._LibraryPcdList = []\r
-        return self._LibraryPcdList\r
+    @cached_property\r
+    def LibraryPcdList(self):\r
+        if self.IsLibrary:\r
+            return []\r
+        RetVal = []\r
+        Pcds = set()\r
+        # get PCDs from dependent libraries\r
+        for Library in self.DependentLibraryList:\r
+            PcdsInLibrary = OrderedDict()\r
+            ExtendCopyDictionaryLists(self._PcdComments, Library.PcdComments)\r
+            for Key in Library.Pcds:\r
+                # skip duplicated PCDs\r
+                if Key in self.Module.Pcds or Key in Pcds:\r
+                    continue\r
+                Pcds.add(Key)\r
+                PcdsInLibrary[Key] = copy.copy(Library.Pcds[Key])\r
+            RetVal.extend(self.PlatformInfo.ApplyPcdSetting(self.Module, PcdsInLibrary, Library=Library))\r
+        return RetVal\r
 \r
     ## Get the GUID value mapping\r
     #\r
     #   @retval     dict    The mapping between GUID cname and its value\r
     #\r
-    def _GetGuidList(self):\r
-        if self._GuidList is None:\r
-            self._GuidList = OrderedDict()\r
-            self._GuidList.update(self.Module.Guids)\r
-            for Library in self.DependentLibraryList:\r
-                self._GuidList.update(Library.Guids)\r
-                ExtendCopyDictionaryLists(self._GuidComments, Library.GuidComments)\r
-            ExtendCopyDictionaryLists(self._GuidComments, self.Module.GuidComments)\r
-        return self._GuidList\r
-\r
+    @cached_property\r
+    def GuidList(self):\r
+        RetVal = OrderedDict(self.Module.Guids)\r
+        for Library in self.DependentLibraryList:\r
+            RetVal.update(Library.Guids)\r
+            ExtendCopyDictionaryLists(self._GuidComments, Library.GuidComments)\r
+        ExtendCopyDictionaryLists(self._GuidComments, self.Module.GuidComments)\r
+        return RetVal\r
+\r
+    @cached_property\r
     def GetGuidsUsedByPcd(self):\r
-        if self._GuidsUsedByPcd is None:\r
-            self._GuidsUsedByPcd = OrderedDict()\r
-            self._GuidsUsedByPcd.update(self.Module.GetGuidsUsedByPcd())\r
-            for Library in self.DependentLibraryList:\r
-                self._GuidsUsedByPcd.update(Library.GetGuidsUsedByPcd())\r
-        return self._GuidsUsedByPcd\r
+        RetVal = OrderedDict(self.Module.GetGuidsUsedByPcd())\r
+        for Library in self.DependentLibraryList:\r
+            RetVal.update(Library.GetGuidsUsedByPcd())\r
+        return RetVal\r
     ## Get the protocol value mapping\r
     #\r
     #   @retval     dict    The mapping between protocol cname and its value\r
     #\r
-    def _GetProtocolList(self):\r
-        if self._ProtocolList is None:\r
-            self._ProtocolList = OrderedDict()\r
-            self._ProtocolList.update(self.Module.Protocols)\r
-            for Library in self.DependentLibraryList:\r
-                self._ProtocolList.update(Library.Protocols)\r
-                ExtendCopyDictionaryLists(self._ProtocolComments, Library.ProtocolComments)\r
-            ExtendCopyDictionaryLists(self._ProtocolComments, self.Module.ProtocolComments)\r
-        return self._ProtocolList\r
+    @cached_property\r
+    def ProtocolList(self):\r
+        RetVal = OrderedDict(self.Module.Protocols)\r
+        for Library in self.DependentLibraryList:\r
+            RetVal.update(Library.Protocols)\r
+            ExtendCopyDictionaryLists(self._ProtocolComments, Library.ProtocolComments)\r
+        ExtendCopyDictionaryLists(self._ProtocolComments, self.Module.ProtocolComments)\r
+        return RetVal\r
 \r
     ## Get the PPI value mapping\r
     #\r
     #   @retval     dict    The mapping between PPI cname and its value\r
     #\r
-    def _GetPpiList(self):\r
-        if self._PpiList is None:\r
-            self._PpiList = OrderedDict()\r
-            self._PpiList.update(self.Module.Ppis)\r
-            for Library in self.DependentLibraryList:\r
-                self._PpiList.update(Library.Ppis)\r
-                ExtendCopyDictionaryLists(self._PpiComments, Library.PpiComments)\r
-            ExtendCopyDictionaryLists(self._PpiComments, self.Module.PpiComments)\r
-        return self._PpiList\r
+    @cached_property\r
+    def PpiList(self):\r
+        RetVal = OrderedDict(self.Module.Ppis)\r
+        for Library in self.DependentLibraryList:\r
+            RetVal.update(Library.Ppis)\r
+            ExtendCopyDictionaryLists(self._PpiComments, Library.PpiComments)\r
+        ExtendCopyDictionaryLists(self._PpiComments, self.Module.PpiComments)\r
+        return RetVal\r
 \r
     ## Get the list of include search path\r
     #\r
     #   @retval     list                    The list path\r
     #\r
-    def _GetIncludePathList(self):\r
-        if self._IncludePathList is None:\r
-            self._IncludePathList = []\r
-            if self.AutoGenVersion < 0x00010005:\r
-                for Inc in self.Module.Includes:\r
-                    if Inc not in self._IncludePathList:\r
-                        self._IncludePathList.append(Inc)\r
-                    # for Edk modules\r
-                    Inc = path.join(Inc, self.Arch.capitalize())\r
-                    if os.path.exists(Inc) and Inc not in self._IncludePathList:\r
-                        self._IncludePathList.append(Inc)\r
-                # Edk module needs to put DEBUG_DIR at the end of search path and not to use SOURCE_DIR all the time\r
-                self._IncludePathList.append(self.DebugDir)\r
-            else:\r
-                self._IncludePathList.append(self.MetaFile.Dir)\r
-                self._IncludePathList.append(self.DebugDir)\r
-\r
-            for Package in self.Module.Packages:\r
-                PackageDir = mws.join(self.WorkspaceDir, Package.MetaFile.Dir)\r
-                if PackageDir not in self._IncludePathList:\r
-                    self._IncludePathList.append(PackageDir)\r
-                IncludesList = Package.Includes\r
-                if Package._PrivateIncludes:\r
-                    if not self.MetaFile.Path.startswith(PackageDir):\r
-                        IncludesList = list(set(Package.Includes).difference(set(Package._PrivateIncludes)))\r
-                for Inc in IncludesList:\r
-                    if Inc not in self._IncludePathList:\r
-                        self._IncludePathList.append(str(Inc))\r
-        return self._IncludePathList\r
-\r
-    def _GetIncludePathLength(self):\r
-        return sum(len(inc)+1 for inc in self._IncludePathList)\r
+    @cached_property\r
+    def IncludePathList(self):\r
+        RetVal = []\r
+        if self.AutoGenVersion < 0x00010005:\r
+            for Inc in self.Module.Includes:\r
+                if Inc not in RetVal:\r
+                    RetVal.append(Inc)\r
+                # for Edk modules\r
+                Inc = path.join(Inc, self.Arch.capitalize())\r
+                if os.path.exists(Inc) and Inc not in RetVal:\r
+                    RetVal.append(Inc)\r
+            # Edk module needs to put DEBUG_DIR at the end of search path and not to use SOURCE_DIR all the time\r
+            RetVal.append(self.DebugDir)\r
+        else:\r
+            RetVal.append(self.MetaFile.Dir)\r
+            RetVal.append(self.DebugDir)\r
+\r
+        for Package in self.Module.Packages:\r
+            PackageDir = mws.join(self.WorkspaceDir, Package.MetaFile.Dir)\r
+            if PackageDir not in RetVal:\r
+                RetVal.append(PackageDir)\r
+            IncludesList = Package.Includes\r
+            if Package._PrivateIncludes:\r
+                if not self.MetaFile.Path.startswith(PackageDir):\r
+                    IncludesList = list(set(Package.Includes).difference(set(Package._PrivateIncludes)))\r
+            for Inc in IncludesList:\r
+                if Inc not in RetVal:\r
+                    RetVal.append(str(Inc))\r
+        return RetVal\r
+\r
+    @cached_property\r
+    def IncludePathLength(self):\r
+        return sum(len(inc)+1 for inc in self.IncludePathList)\r
 \r
     ## Get HII EX PCDs which maybe used by VFR\r
     #\r
@@ -3687,12 +3499,12 @@ class ModuleAutoGen(AutoGen):
         for SourceFile in self.Module.Sources:\r
             if SourceFile.Type.upper() == ".VFR" :\r
                 #\r
-                # search the .map file to find the offset of vfr binary in the PE32+/TE file. \r
+                # search the .map file to find the offset of vfr binary in the PE32+/TE file.\r
                 #\r
                 VfrUniBaseName[SourceFile.BaseName] = (SourceFile.BaseName + "Bin")\r
             elif SourceFile.Type.upper() == ".UNI" :\r
                 #\r
-                # search the .map file to find the offset of Uni strings binary in the PE32+/TE file. \r
+                # search the .map file to find the offset of Uni strings binary in the PE32+/TE file.\r
                 #\r
                 VfrUniBaseName["UniOffsetName"] = (self.Name + "Strings")\r
 \r
@@ -3710,10 +3522,10 @@ class ModuleAutoGen(AutoGen):
         try:\r
             fInputfile = open(UniVfrOffsetFileName, "wb+", 0)\r
         except:\r
-            EdkLogger.error("build", FILE_OPEN_FAILURE, "File open failed for %s" % UniVfrOffsetFileName,None)\r
+            EdkLogger.error("build", FILE_OPEN_FAILURE, "File open failed for %s" % UniVfrOffsetFileName, None)\r
 \r
-        # Use a instance of StringIO to cache data\r
-        fStringIO = StringIO('')  \r
+        # Use a instance of BytesIO to cache data\r
+        fStringIO = BytesIO('')\r
 \r
         for Item in VfrUniOffsetList:\r
             if (Item[0].find("Strings") != -1):\r
@@ -3724,7 +3536,7 @@ class ModuleAutoGen(AutoGen):
                 #\r
                 UniGuid = [0xe0, 0xc5, 0x13, 0x89, 0xf6, 0x33, 0x86, 0x4d, 0x9b, 0xf1, 0x43, 0xef, 0x89, 0xfc, 0x6, 0x66]\r
                 UniGuid = [chr(ItemGuid) for ItemGuid in UniGuid]\r
-                fStringIO.write(''.join(UniGuid))            \r
+                fStringIO.write(''.join(UniGuid))\r
                 UniValue = pack ('Q', int (Item[1], 16))\r
                 fStringIO.write (UniValue)\r
             else:\r
@@ -3735,17 +3547,17 @@ class ModuleAutoGen(AutoGen):
                 #\r
                 VfrGuid = [0xb4, 0x7c, 0xbc, 0xd0, 0x47, 0x6a, 0x5f, 0x49, 0xaa, 0x11, 0x71, 0x7, 0x46, 0xda, 0x6, 0xa2]\r
                 VfrGuid = [chr(ItemGuid) for ItemGuid in VfrGuid]\r
-                fStringIO.write(''.join(VfrGuid))                   \r
+                fStringIO.write(''.join(VfrGuid))\r
                 VfrValue = pack ('Q', int (Item[1], 16))\r
                 fStringIO.write (VfrValue)\r
         #\r
         # write data into file.\r
         #\r
-        try :  \r
+        try :\r
             fInputfile.write (fStringIO.getvalue())\r
         except:\r
             EdkLogger.error("build", FILE_WRITE_FAILURE, "Write data to file %s failed, please check whether the "\r
-                            "file been locked or using by other applications." %UniVfrOffsetFileName,None)\r
+                            "file been locked or using by other applications." %UniVfrOffsetFileName, None)\r
 \r
         fStringIO.close ()\r
         fInputfile.close ()\r
@@ -3761,15 +3573,15 @@ class ModuleAutoGen(AutoGen):
 \r
         if self.IsAsBuiltInfCreated:\r
             return\r
-            \r
+\r
         # Skip the following code for EDK I inf\r
         if self.AutoGenVersion < 0x00010005:\r
             return\r
-            \r
+\r
         # Skip the following code for libraries\r
         if self.IsLibrary:\r
             return\r
-            \r
+\r
         # Skip the following code for modules with no source files\r
         if not self.SourceFileList:\r
             return\r
@@ -3777,7 +3589,7 @@ class ModuleAutoGen(AutoGen):
         # Skip the following code for modules without any binary files\r
         if self.BinaryFileList:\r
             return\r
-            \r
+\r
         ### TODO: How to handles mixed source and binary modules\r
 \r
         # Find all DynamicEx and PatchableInModule PCDs used by this module and dependent libraries\r
@@ -3797,9 +3609,8 @@ class ModuleAutoGen(AutoGen):
                     PcdCheckList.append((Pcd.TokenCName, Pcd.TokenSpaceGuidCName, TAB_PCDS_DYNAMIC_EX))\r
                     PcdCheckList.append((Pcd.TokenCName, Pcd.TokenSpaceGuidCName, TAB_PCDS_DYNAMIC))\r
                     PcdTokenSpaceList.append(Pcd.TokenSpaceGuidCName)\r
-        GuidList = OrderedDict()\r
-        GuidList.update(self.GuidList)\r
-        for TokenSpace in self.GetGuidsUsedByPcd():\r
+        GuidList = OrderedDict(self.GuidList)\r
+        for TokenSpace in self.GetGuidsUsedByPcd:\r
             # If token space is not referred by patch PCD or Ex PCD, remove the GUID from GUID list\r
             # The GUIDs in GUIDs section should really be the GUIDs in source INF or referred by Ex an patch PCDs\r
             if TokenSpace not in PcdTokenSpaceList and TokenSpace in GuidList:\r
@@ -4026,11 +3837,9 @@ class ModuleAutoGen(AutoGen):
                     PcdItem = PcdComments + '\n  ' + PcdItem\r
                 AsBuiltInfDict['patchablepcd_item'].append(PcdItem)\r
 \r
-        HiiPcds = set()\r
         for Pcd in Pcds + VfrPcds:\r
             PcdCommentList = []\r
             HiiInfo = ''\r
-            SkuId = ''\r
             TokenCName = Pcd.TokenCName\r
             for PcdItem in GlobalData.MixedPcd:\r
                 if (Pcd.TokenCName, Pcd.TokenSpaceGuidCName) in GlobalData.MixedPcd[PcdItem]:\r
@@ -4039,16 +3848,8 @@ class ModuleAutoGen(AutoGen):
             if Pcd.Type == TAB_PCDS_DYNAMIC_EX_HII:\r
                 for SkuName in Pcd.SkuInfoList:\r
                     SkuInfo = Pcd.SkuInfoList[SkuName]\r
-                    SkuId = SkuInfo.SkuId\r
                     HiiInfo = '## %s|%s|%s' % (SkuInfo.VariableName, SkuInfo.VariableGuid, SkuInfo.VariableOffset)\r
                     break\r
-            if SkuId:\r
-                #\r
-                # Don't generate duplicated HII PCD\r
-                #\r
-                if (SkuId, Pcd.TokenSpaceGuidCName, Pcd.TokenCName) in HiiPcds:\r
-                    continue\r
-                HiiPcds.add((SkuId, Pcd.TokenSpaceGuidCName, Pcd.TokenCName))\r
             if (Pcd.TokenSpaceGuidCName, Pcd.TokenCName) in self._PcdComments:\r
                 PcdCommentList = self._PcdComments[Pcd.TokenSpaceGuidCName, Pcd.TokenCName][:]\r
             if HiiInfo:\r
@@ -4061,7 +3862,7 @@ class ModuleAutoGen(AutoGen):
                             UsageIndex = Index\r
                             break\r
                 if UsageIndex != -1:\r
-                    PcdCommentList[UsageIndex] = '## %s %s %s' % (UsageStr, HiiInfo, PcdCommentList[UsageIndex].replace(UsageStr, '')) \r
+                    PcdCommentList[UsageIndex] = '## %s %s %s' % (UsageStr, HiiInfo, PcdCommentList[UsageIndex].replace(UsageStr, ''))\r
                 else:\r
                     PcdCommentList.append('## UNDEFINED ' + HiiInfo)\r
             PcdComments = '\n  '.join(PcdCommentList)\r
@@ -4076,7 +3877,7 @@ class ModuleAutoGen(AutoGen):
         # Generated LibraryClasses section in comments.\r
         for Library in self.LibraryAutoGenList:\r
             AsBuiltInfDict['libraryclasses_item'].append(Library.MetaFile.File.replace('\\', '/'))\r
-        \r
+\r
         # Generated UserExtensions TianoCore section.\r
         # All tianocore user extensions are copied.\r
         UserExtStr = ''\r
@@ -4090,12 +3891,12 @@ class ModuleAutoGen(AutoGen):
         # Generated depex expression section in comments.\r
         DepexExpresion = self._GetDepexExpresionString()\r
         AsBuiltInfDict['depexsection_item'] = DepexExpresion if DepexExpresion else ''\r
-        \r
+\r
         AsBuiltInf = TemplateString()\r
         AsBuiltInf.Append(gAsBuiltInfHeaderString.Replace(AsBuiltInfDict))\r
-        \r
+\r
         SaveFileOnChange(os.path.join(self.OutputDir, self.Name + '.inf'), str(AsBuiltInf), False)\r
-        \r
+\r
         self.IsAsBuiltInfCreated = True\r
         if GlobalData.gBinCacheDest:\r
             self.CopyModuleToCache()\r
@@ -4148,13 +3949,31 @@ class ModuleAutoGen(AutoGen):
     #   @param      CreateLibraryMakeFile   Flag indicating if or not the makefiles of\r
     #                                       dependent libraries will be created\r
     #\r
+    @cached_class_function\r
     def CreateMakeFile(self, CreateLibraryMakeFile=True, GenFfsList = []):\r
+        # nest this function inside it's only caller.\r
+        def CreateTimeStamp():\r
+            FileSet = {self.MetaFile.Path}\r
+\r
+            for SourceFile in self.Module.Sources:\r
+                FileSet.add (SourceFile.Path)\r
+\r
+            for Lib in self.DependentLibraryList:\r
+                FileSet.add (Lib.MetaFile.Path)\r
+\r
+            for f in self.AutoGenDepSet:\r
+                FileSet.add (f.Path)\r
+\r
+            if os.path.exists (self.TimeStampPath):\r
+                os.remove (self.TimeStampPath)\r
+            with open(self.TimeStampPath, 'w+') as file:\r
+                for f in FileSet:\r
+                    print(f, file=file)\r
+\r
         # Ignore generating makefile when it is a binary module\r
         if self.IsBinaryModule:\r
             return\r
 \r
-        if self.IsMakeFileCreated:\r
-            return\r
         self.GenFfsList = GenFfsList\r
         if not self.IsLibrary and CreateLibraryMakeFile:\r
             for LibraryAutoGen in self.LibraryAutoGenList:\r
@@ -4174,13 +3993,12 @@ class ModuleAutoGen(AutoGen):
             EdkLogger.debug(EdkLogger.DEBUG_9, "Skipped the generation of makefile for module %s [%s]" %\r
                             (self.Name, self.Arch))\r
 \r
-        self.CreateTimeStamp(Makefile)\r
-        self.IsMakeFileCreated = True\r
+        CreateTimeStamp()\r
 \r
     def CopyBinaryFiles(self):\r
         for File in self.Module.Binaries:\r
             SrcPath = File.Path\r
-            DstPath = os.path.join(self.OutputDir , os.path.basename(SrcPath))\r
+            DstPath = os.path.join(self.OutputDir, os.path.basename(SrcPath))\r
             CopyLongFilePath(SrcPath, DstPath)\r
     ## Create autogen code for the module and its dependent libraries\r
     #\r
@@ -4232,7 +4050,7 @@ class ModuleAutoGen(AutoGen):
             Dpx = GenDepex.DependencyExpression(self.DepexList[ModuleType], ModuleType, True)\r
             DpxFile = gAutoGenDepexFileName % {"module_name" : self.Name}\r
 \r
-            if len(Dpx.PostfixNotation) <> 0:\r
+            if len(Dpx.PostfixNotation) != 0:\r
                 self.DepexGenerated = True\r
 \r
             if Dpx.Generate(path.join(self.OutputDir, DpxFile)):\r
@@ -4254,11 +4072,11 @@ class ModuleAutoGen(AutoGen):
         return AutoGenList\r
 \r
     ## Summarize the ModuleAutoGen objects of all libraries used by this module\r
-    def _GetLibraryAutoGenList(self):\r
-        if self._LibraryAutoGenList is None:\r
-            self._LibraryAutoGenList = []\r
-            for Library in self.DependentLibraryList:\r
-                La = ModuleAutoGen(\r
+    @cached_property\r
+    def LibraryAutoGenList(self):\r
+        RetVal = []\r
+        for Library in self.DependentLibraryList:\r
+            La = ModuleAutoGen(\r
                         self.Workspace,\r
                         Library.MetaFile,\r
                         self.BuildTarget,\r
@@ -4266,11 +4084,11 @@ class ModuleAutoGen(AutoGen):
                         self.Arch,\r
                         self.PlatformInfo.MetaFile\r
                         )\r
-                if La not in self._LibraryAutoGenList:\r
-                    self._LibraryAutoGenList.append(La)\r
-                    for Lib in La.CodaTargetList:\r
-                        self._ApplyBuildRule(Lib.Target, TAB_UNKNOWN_FILE)\r
-        return self._LibraryAutoGenList\r
+            if La not in RetVal:\r
+                RetVal.append(La)\r
+                for Lib in La.CodaTargetList:\r
+                    self._ApplyBuildRule(Lib.Target, TAB_UNKNOWN_FILE)\r
+        return RetVal\r
 \r
     def GenModuleHash(self):\r
         if self.Arch not in GlobalData.gModuleHash:\r
@@ -4316,21 +4134,24 @@ class ModuleAutoGen(AutoGen):
     def CanSkipbyHash(self):\r
         if GlobalData.gUseHashCache:\r
             return not self.GenModuleHash()\r
+        return False\r
 \r
     ## Decide whether we can skip the ModuleAutoGen process\r
     #  If any source file is newer than the module than we cannot skip\r
     #\r
     def CanSkip(self):\r
-        if not os.path.exists(self.GetTimeStampPath()):\r
+        if self.MakeFileDir in GlobalData.gSikpAutoGenCache:\r
+            return True\r
+        if not os.path.exists(self.TimeStampPath):\r
             return False\r
         #last creation time of the module\r
-        DstTimeStamp = os.stat(self.GetTimeStampPath())[8]\r
+        DstTimeStamp = os.stat(self.TimeStampPath)[8]\r
 \r
         SrcTimeStamp = self.Workspace._SrcTimeStamp\r
         if SrcTimeStamp > DstTimeStamp:\r
             return False\r
 \r
-        with open(self.GetTimeStampPath(),'r') as f:\r
+        with open(self.TimeStampPath,'r') as f:\r
             for source in f:\r
                 source = source.rstrip('\n')\r
                 if not os.path.exists(source):\r
@@ -4339,86 +4160,9 @@ class ModuleAutoGen(AutoGen):
                     ModuleAutoGen.TimeDict[source] = os.stat(source)[8]\r
                 if ModuleAutoGen.TimeDict[source] > DstTimeStamp:\r
                     return False\r
+        GlobalData.gSikpAutoGenCache.add(self.MakeFileDir)\r
         return True\r
 \r
-    def GetTimeStampPath(self):\r
-        if self._TimeStampPath is None:\r
-            self._TimeStampPath = os.path.join(self.MakeFileDir, 'AutoGenTimeStamp')\r
-        return self._TimeStampPath\r
-    def CreateTimeStamp(self, Makefile):\r
-\r
-        FileSet = {self.MetaFile.Path}\r
-\r
-        for SourceFile in self.Module.Sources:\r
-            FileSet.add (SourceFile.Path)\r
-\r
-        for Lib in self.DependentLibraryList:\r
-            FileSet.add (Lib.MetaFile.Path)\r
-\r
-        for f in self.AutoGenDepSet:\r
-            FileSet.add (f.Path)\r
-\r
-        if os.path.exists (self.GetTimeStampPath()):\r
-            os.remove (self.GetTimeStampPath())\r
-        with open(self.GetTimeStampPath(), 'w+') as file:\r
-            for f in FileSet:\r
-                print >> file, f\r
-\r
-    Module          = property(_GetModule)\r
-    Name            = property(_GetBaseName)\r
-    Guid            = property(_GetGuid)\r
-    Version         = property(_GetVersion)\r
-    ModuleType      = property(_GetModuleType)\r
-    ComponentType   = property(_GetComponentType)\r
-    BuildType       = property(_GetBuildType)\r
-    PcdIsDriver     = property(_GetPcdIsDriver)\r
-    AutoGenVersion  = property(_GetAutoGenVersion)\r
-    Macros          = property(_GetMacros)\r
-    Specification   = property(_GetSpecification)\r
-\r
-    IsLibrary       = property(_IsLibrary)\r
-    IsBinaryModule  = property(_IsBinaryModule)\r
-    BuildDir        = property(_GetBuildDir)\r
-    OutputDir       = property(_GetOutputDir)\r
-    FfsOutputDir    = property(_GetFfsOutputDir)\r
-    DebugDir        = property(_GetDebugDir)\r
-    MakeFileDir     = property(_GetMakeFileDir)\r
-    CustomMakefile  = property(_GetCustomMakefile)\r
-\r
-    IncludePathList = property(_GetIncludePathList)\r
-    IncludePathLength = property(_GetIncludePathLength)\r
-    AutoGenFileList = property(_GetAutoGenFileList)\r
-    UnicodeFileList = property(_GetUnicodeFileList)\r
-    VfrFileList     = property(_GetVfrFileList)\r
-    SourceFileList  = property(_GetSourceFileList)\r
-    BinaryFileList  = property(_GetBinaryFiles) # FileType : [File List]\r
-    Targets         = property(_GetTargets)\r
-    IntroTargetList = property(_GetIntroTargetList)\r
-    CodaTargetList  = property(_GetFinalTargetList)\r
-    FileTypes       = property(_GetFileTypes)\r
-    BuildRules      = property(_GetBuildRules)\r
-    IdfFileList     = property(_GetIdfFileList)\r
-\r
-    DependentPackageList    = property(_GetDependentPackageList)\r
-    DependentLibraryList    = property(_GetLibraryList)\r
-    LibraryAutoGenList      = property(_GetLibraryAutoGenList)\r
-    DerivedPackageList      = property(_GetDerivedPackageList)\r
-\r
-    ModulePcdList           = property(_GetModulePcdList)\r
-    LibraryPcdList          = property(_GetLibraryPcdList)\r
-    GuidList                = property(_GetGuidList)\r
-    ProtocolList            = property(_GetProtocolList)\r
-    PpiList                 = property(_GetPpiList)\r
-    DepexList               = property(_GetDepexTokenList)\r
-    DxsFile                 = property(_GetDxsFile)\r
-    DepexExpressionDict     = property(_GetDepexExpressionTokenList)\r
-    BuildOption             = property(_GetModuleBuildOption)\r
-    BuildOptionIncPathList  = property(_GetBuildOptionIncPathList)\r
-    BuildCommand            = property(_GetBuildCommand)\r
-    \r
-    FixedAtBuildPcds         = property(_GetFixedAtBuildPcds)\r
-\r
-# This acts like the main() function for the script, unless it is 'import'ed into another script.\r
-if __name__ == '__main__':\r
-    pass\r
-\r
+    @cached_property\r
+    def TimeStampPath(self):\r
+        return os.path.join(self.MakeFileDir, 'AutoGenTimeStamp')\r