Browse Source

compiler: set nil after free

mattias 5 days ago
parent
commit
789b361482
54 changed files with 524 additions and 65 deletions
  1. 1 0
      compiler/objcdef.pas
  2. 31 0
      compiler/objcgutl.pas
  3. 40 9
      compiler/ogbase.pas
  4. 5 0
      compiler/ogcoff.pas
  5. 9 0
      compiler/ogelf.pas
  6. 7 1
      compiler/ogmacho.pas
  7. 4 0
      compiler/ognlm.pas
  8. 83 1
      compiler/ogomf.pas
  9. 1 0
      compiler/ogrel.pas
  10. 25 7
      compiler/ogwasm.pas
  11. 3 2
      compiler/omfbase.pas
  12. 1 0
      compiler/optconstprop.pas
  13. 7 6
      compiler/optcse.pas
  14. 2 0
      compiler/optdfa.pas
  15. 11 0
      compiler/options.pas
  16. 1 0
      compiler/optloop.pas
  17. 2 0
      compiler/opttail.pas
  18. 6 0
      compiler/owar.pas
  19. 2 0
      compiler/owbase.pas
  20. 17 0
      compiler/owomflib.pas
  21. 1 0
      compiler/paramgr.pas
  22. 8 2
      compiler/parser.pas
  23. 1 0
      compiler/pass_1.pas
  24. 13 5
      compiler/pdecl.pas
  25. 3 0
      compiler/pdecobj.pas
  26. 5 1
      compiler/pdecsub.pas
  27. 17 5
      compiler/pdecvar.pas
  28. 2 0
      compiler/pexports.pas
  29. 26 5
      compiler/pexpr.pas
  30. 1 0
      compiler/pgentype.pas
  31. 26 3
      compiler/pgenutil.pas
  32. 12 0
      compiler/pinline.pas
  33. 11 0
      compiler/pkgutil.pas
  34. 10 0
      compiler/pmodules.pas
  35. 5 2
      compiler/procdefutil.pas
  36. 6 0
      compiler/procinfo.pas
  37. 7 0
      compiler/psabiehpi.pas
  38. 13 1
      compiler/pstatmnt.pas
  39. 5 0
      compiler/psub.pas
  40. 1 0
      compiler/ptconst.pas
  41. 6 0
      compiler/ptype.pas
  42. 2 0
      compiler/rasm.pas
  43. 2 1
      compiler/rautils.pas
  44. 7 1
      compiler/rgobj.pas
  45. 24 2
      compiler/scanner.pas
  46. 1 0
      compiler/switches.pas
  47. 3 0
      compiler/symbase.pas
  48. 2 1
      compiler/symcreat.pas
  49. 11 1
      compiler/symdef.pas
  50. 11 4
      compiler/symsym.pas
  51. 11 0
      compiler/symtable.pas
  52. 7 2
      compiler/symtype.pas
  53. 1 0
      compiler/verbose.pas
  54. 5 3
      compiler/wpobase.pas

+ 1 - 0
compiler/objcdef.pas

@@ -140,6 +140,7 @@ implementation
         for i:=0 to variantstarts.count-1 do
           encodedstr:=encodedstr+'})';
         variantstarts.free;
+        variantstarts := nil;
         encodedstr:=encodedstr+'}';
         result:=true
       end;

+ 31 - 0
compiler/objcgutl.pas

@@ -173,6 +173,7 @@ procedure objcreatestringpoolentryintern(p: pchar; len: longint; pooltype: tcons
           tcb.get_final_asmlist(strlab,def,stringsec,strlab.name,1)
         );
         tcb.free;
+        tcb := nil;
         def:=cpointerdef.getreusable(def);
       end
     else
@@ -207,6 +208,7 @@ procedure objcfinishstringrefpoolentry(entry: phashsetitem; stringpool: tconstpo
           tcb.get_final_asmlist(reflab,strdef,refsec,reflab.name,sizeof(pint))
           );
         tcb.free;
+        tcb := nil;
 
         { in case of a class reference, also add a lazy symbol reference for
           the class (the linker requires this for the fragile ABI). }
@@ -252,6 +254,7 @@ procedure objcfinishclassrefnfpoolentry(entry: phashsetitem; classdef: tobjectde
           tcb.get_final_asmlist(reflab,voidpointertype,sec_objc_cls_refs,reflab.name,sizeof(pint))
         );
         tcb.free;
+        tcb := nil;
       end;
   end;
 
@@ -371,6 +374,7 @@ procedure tobjcrttiwriter.gen_objc_methods(list: tasmlist; objccls: tobjectdef;
       )
     );
     tcb.free;
+    tcb := nil;
   end;
 
 
@@ -420,9 +424,13 @@ procedure tobjcrttiwriter.gen_objc_protocol_elements(list: tasmlist; protocol: t
       optclssym:=nil;
 
     reqinstmlist.Free;
+    reqinstmlist := nil;
     reqclsmlist.Free;
+    reqclsmlist := nil;
     optinstmlist.Free;
+    optinstmlist := nil;
     optclsmlist.Free;
+    optclsmlist := nil;
 end;
 
 
@@ -498,6 +506,7 @@ procedure tobjcrttiwriter.gen_objc_protocol_list(list: tasmlist; protolist: tfpo
       )
     );
     tcb.free;
+    tcb := nil;
     { the symbol will point to a record }
   end;
 
@@ -547,6 +556,7 @@ begin
       listsym,tcb.end_anonymous_record,section,sectname,sizeof(pint))
   );
   tcb.free;
+  tcb := nil;
 end;
 
 
@@ -609,11 +619,17 @@ constructor tobjcrttiwriter.create(_abi: tobjcabi);
 destructor tobjcrttiwriter.destroy;
   begin
     classdefs.free;
+    classdefs := nil;
     classsyms.free;
+    classsyms := nil;
     classrttidefs.free;
+    classrttidefs := nil;
     catrttidefs.free;
+    catrttidefs := nil;
     catdefs.free;
+    catdefs := nil;
     catsyms.free;
+    catsyms := nil;
     inherited destroy;
   end;
 
@@ -721,6 +737,7 @@ function tobjcrttiwriter_fragile.gen_objc_protocol_ext(list: TAsmList; optinstsy
           )
         );
         tcb.free;
+        tcb := nil;
       end
     else
       Result:=nil;
@@ -773,6 +790,7 @@ procedure tobjcrttiwriter_fragile.gen_objc_protocol(list:TAsmList; protocol: tob
       )
     );
     tcb.free;
+    tcb := nil;
   end;
 
 
@@ -844,6 +862,7 @@ procedure tobjcrttiwriter_fragile.gen_objc_category_sections(list:TAsmList; objc
       )
     );
     tcb.free;
+    tcb := nil;
 
     catlabel:=catsym;
     catlabeldef:=catdef;
@@ -1036,6 +1055,7 @@ procedure tobjcrttiwriter_fragile.gen_objc_classes_sections(list:TAsmList; objcl
       )
     );
     tcb.free;
+    tcb := nil;
 
     classlabel:=clssym;
     classlabeldef:=clsDef;
@@ -1135,6 +1155,7 @@ procedure tobjcrttiwriter_fragile.gen_objc_info_sections(list: tasmlist);
           end;
       end;
     superclasses.free;
+    superclasses := nil;
     { reference symbols for all classes and categories defined in this unit }
     for i:=0 to classdefs.count-1 do
       list.concat(tai_symbol.Createname_global_value('.objc_class_name_'+tobjectdef(classdefs[i]).objextname^,AT_DATA,0,0,voidpointertype));
@@ -1240,6 +1261,7 @@ procedure tobjcrttiwriter_nonfragile.gen_objc_ivars(list: tasmlist; objccls: tob
                 )
               );
               tcb.free;
+              tcb := nil;
               inc(vcnt);
             end
           else
@@ -1289,6 +1311,7 @@ procedure tobjcrttiwriter_nonfragile.gen_objc_ivars(list: tasmlist; objccls: tob
       )
     );
     tcb.free;
+    tcb := nil;
   end;
 
 
@@ -1395,6 +1418,7 @@ procedure tobjcrttiwriter_nonfragile.gen_objc_protocol(list: tasmlist; protocol:
       )
     );
     tcb.free;
+    tcb := nil;
   end;
 
 (*
@@ -1455,6 +1479,7 @@ procedure tobjcrttiwriter_nonfragile.gen_objc_category_sections(list:TAsmList; o
       )
     );
     tcb.free;
+    tcb := nil;
 
     catlabel:=catsym;
     catlabeldef:=catdef;
@@ -1667,6 +1692,7 @@ procedure tobjcrttiwriter_nonfragile.gen_objc_class_ro_part(list: tasmlist; objc
       )
     );
     tcb.free;
+    tcb := nil;
     classrolabel:=rosym;
   end;
 
@@ -1781,6 +1807,7 @@ procedure tobjcrttiwriter_nonfragile.gen_objc_classes_sections(list:TAsmList; ob
       )
     );
     metatcb.free;
+    metatcb := nil;
 
     { 2) regular class declaration }
     { the isa }
@@ -1801,6 +1828,7 @@ procedure tobjcrttiwriter_nonfragile.gen_objc_classes_sections(list:TAsmList; ob
       )
     );
     isatcb.free;
+    isatcb := nil;
 
     classlabel:=clssym;
     classlabeldef:=classdef;
@@ -1888,7 +1916,9 @@ procedure tobjcrttiwriter_nonfragile.gen_objc_info_sections(list: tasmlist);
     addclasslist(list,sec_objc_nlcatlist,target_asm.labelprefix+'_OBJC_LABEL_NONLAZY_CATEGORY_$',nonlazycategories);
 
     nonlazyclasses.free;
+    nonlazyclasses := nil;
     nonlazycategories.free;
+    nonlazycategories := nil;
     { the non-fragile abi doesn't have any module info, nor lazy references
       to used classes or to parent classes }
   end;
@@ -1920,6 +1950,7 @@ procedure MaybeGenerateObjectiveCImageInfo(globalst, localst: tsymtable);
         objcrttiwriter.gen_objc_rtti_sections(current_asmdata.asmlists[al_objc_data],localst);
         objcrttiwriter.gen_objc_info_sections(current_asmdata.asmlists[al_objc_data]);
         objcrttiwriter.free;
+        objcrttiwriter := nil;
       end;
   end;
 

+ 40 - 9
compiler/ogbase.pas

@@ -1075,10 +1075,15 @@ implementation
     destructor TObjSection.destroy;
       begin
         if assigned(Data) then
-          Data.Free;
+          begin
+            FData.Free;
+            FData := nil;
+          end;
         stringdispose(FCachedFullName);
         ObjRelocations.Free;
+        ObjRelocations := nil;
         VTRefList.Free;
+        VTRefList := nil;
         inherited destroy;
       end;
 
@@ -1432,17 +1437,21 @@ implementation
 {$endif}
         ResetCachedAsmSymbols;
         FCachedAsmSymbolList.free;
+        FCachedAsmSymbolList := nil;
         FObjSymbolList.free;
+        FObjSymbolList := nil;
 {$ifdef MEMDEBUG}
         MemObjSymbols.Stop;
 {$endif}
-        GroupsList.free;
+        FGroupsList.free;
+        FGroupsList := nil;
 
         { Sections }
 {$ifdef MEMDEBUG}
         MemObjSections.Start;
 {$endif}
         FObjSectionList.free;
+        FObjSectionList := nil;
 {$ifdef MEMDEBUG}
         MemObjSections.Stop;
 {$endif}
@@ -2125,6 +2134,7 @@ implementation
     destructor TExeVTable.Destroy;
       begin
         ChildList.Free;
+        ChildList := nil;
         if assigned(EntryArray) then
           Freemem(EntryArray);
       end;
@@ -2220,7 +2230,8 @@ implementation
 
     destructor TExeSection.destroy;
       begin
-        ObjSectionList.Free;
+        FObjSectionList.Free;
+        FObjSectionList := nil;
         inherited destroy;
       end;
 
@@ -2285,6 +2296,7 @@ implementation
     destructor TStaticLibrary.destroy;
       begin
         FPayload.Free;
+        FPayload := nil;
         inherited destroy;
       end;
 
@@ -2325,7 +2337,8 @@ implementation
 
     destructor TImportLibrary.destroy;
       begin
-        ImportSymbolList.Free;
+        FImportSymbolList.Free;
+        FImportSymbolList := nil;
         inherited destroy;
       end;
 
@@ -2394,16 +2407,27 @@ implementation
     destructor TExeOutput.destroy;
       begin
         FExeSymbolList.free;
-        UnresolvedExeSymbols.free;
-        ExternalObjSymbols.free;
+        FExeSymbolList := nil;
+        FUnresolvedExeSymbols.free;
+        FUnresolvedExeSymbols := nil;
+        FExternalObjSymbols.free;
+        FExternalObjSymbols := nil;
         FProvidedObjSymbols.free;
+        FProvidedObjSymbols := nil;
         FIndirectObjSymbols.free;
-        CommonObjSymbols.free;
-        ExeVTableList.free;
+        FIndirectObjSymbols := nil;
+        FCommonObjSymbols.free;
+        FCommonObjSymbols := nil;
+        FExeVTableList.free;
+        FExeVTableList := nil;
         FExeSectionList.free;
+        FExeSectionList := nil;
         ComdatGroups.free;
-        ObjDatalist.free;
+        ComdatGroups := nil;
+        FObjDatalist.free;
+        FObjDatalist := nil;
         FWriter.free;
+        FWriter := nil;
         inherited destroy;
       end;
 
@@ -2590,6 +2614,7 @@ implementation
             CurrExeSec.AddObjSection(objsec);
           end;
         TmpObjSectionList.Free;
+        TmpObjSectionList := nil;
       end;
 
 
@@ -3185,6 +3210,7 @@ implementation
                               objinput:=lib.ObjInputClass.Create;
                               objinput.ReadObjData(lib.ArReader,objdata);
                               objinput.free;
+                              objinput := nil;
                               AddObjData(objdata);
                               LoadObjDataSymbols(objdata);
                               lib.ArReader.CloseFile;
@@ -3313,7 +3339,9 @@ implementation
         if cs_link_opt_vtable in current_settings.globalswitches then
           BuildVTableTree(VTInheritList,VTEntryList);
         VTInheritList.Free;
+        VTInheritList := nil;
         VTEntryList.Free;
+        VTEntryList := nil;
       end;
 
 
@@ -3446,6 +3474,7 @@ implementation
               end;
           end;
         list.Free;
+        list := nil;
       end;
 
 
@@ -4149,6 +4178,8 @@ initialization
 
 finalization
   memobjsymbols.free;
+  memobjsymbols := nil;
   memobjsections.free;
+  memobjsections := nil;
 {$endif MEMDEBUG}
 end.

+ 5 - 0
compiler/ogcoff.pas

@@ -1797,7 +1797,9 @@ const pemagic : array[0..3] of byte = (
     destructor TCoffObjOutput.destroy;
       begin
         FCoffSyms.free;
+        FCoffSyms := nil;
         FCoffStrs.free;
+        FCoffStrs := nil;
         inherited destroy;
       end;
 
@@ -2271,6 +2273,7 @@ const pemagic : array[0..3] of byte = (
     destructor TCoffObjInput.destroy;
       begin
         FCoffSyms.free;
+        FCoffSyms := nil;
         FCoffStrs:=nil;
         FSymTbl:=nil;
         FSecTbl:=nil;
@@ -3404,6 +3407,7 @@ const pemagic : array[0..3] of byte = (
           end;
         { Release }
         FCoffStrs.Free;
+        FCoffStrs := nil;
         result:=true;
       end;
 
@@ -3951,6 +3955,7 @@ const pemagic : array[0..3] of byte = (
             readdllproc(DLLName,FuncName);
           end;
         DLLReader.Free;
+        DLLReader := nil;
       end;
 
 {$ifdef arm}

+ 9 - 0
compiler/ogelf.pas

@@ -741,6 +741,7 @@ implementation
     destructor TElfDynamicObjData.destroy;
       begin
         FVersionDefs.free;
+        FVersionDefs := nil;
         inherited Destroy;
       end;
 
@@ -1832,10 +1833,15 @@ implementation
     destructor TElfExeOutput.Destroy;
       begin
         dyncopysyms.Free;
+        dyncopysyms := nil;
         neededlist.Free;
+        neededlist := nil;
         segmentlist.Free;
+        segmentlist := nil;
         dynsymlist.Free;
+        dynsymlist := nil;
         dynreloclist.Free;
+        dynreloclist := nil;
         if assigned(dynsymnames) then
           FreeMem(dynsymnames);
         stringdispose(FInterpreter);
@@ -2334,7 +2340,9 @@ implementation
         if (newsections.count<>0) then
           ReplaceExeSectionList(allsections);
         newsections.Free;
+        newsections := nil;
         allsections.Free;
+        allsections := nil;
       end;
 
 
@@ -3292,6 +3300,7 @@ implementation
     destructor TElfSegment.Destroy;
       begin
         FSectionList.Free;
+        FSectionList := nil;
         inherited Destroy;
       end;
 

+ 7 - 1
compiler/ogmacho.pas

@@ -1141,13 +1141,19 @@ uses
       TrailZeros;
 
       if not Assigned(strsec) then
-        symstr.Free;
+        begin
+          symstr.Free;
+          symstr := nil;
+        end;
 
       TrailZeros;
 
       mfile.Free;
+      mfile := nil;
       symList.Free;
+      symList := nil;
       IndirIndex.Free;
+      IndirIndex := nil;
     end;
 
 

+ 4 - 0
compiler/ognlm.pas

@@ -398,9 +398,13 @@ end;
     destructor TNLMexeoutput.destroy;
       begin
         nlmImports.Free;
+        nlmImports := nil;
         nlmImpNames.Free;
+        nlmImpNames := nil;
         nlmSymbols.Free;
+        nlmSymbols := nil;
         FexportFunctionOffsets.Free;
+        FexportFunctionOffsets := nil;
         inherited destroy;
       end;
 

+ 83 - 1
compiler/ogomf.pas

@@ -882,6 +882,7 @@ implementation
     destructor TOmfRelocation.Destroy;
       begin
         FOmfFixup.Free;
+        FOmfFixup := nil;
         inherited Destroy;
       end;
 
@@ -1029,6 +1030,7 @@ implementation
     destructor TOmfObjSection.destroy;
       begin
         FLinNumEntries.Free;
+        FLinNumEntries := nil;
         inherited destroy;
       end;
 
@@ -1076,7 +1078,9 @@ implementation
     destructor TOmfObjData.destroy;
       begin
         FExportedSymbolList.Free;
+        FExportedSymbolList := nil;
         FImportLibraryList.Free;
+        FImportLibraryList := nil;
         inherited destroy;
       end;
 
@@ -1419,6 +1423,7 @@ implementation
               ChunkFixupStart:=ChunkFixupEnd+1;
             end;
             RawRecord.Free;
+            RawRecord := nil;
           end;
       end;
 
@@ -1448,7 +1453,9 @@ implementation
               end;
 
             LinNumRec.Free;
+            LinNumRec := nil;
             RawRecord.Free;
+            RawRecord := nil;
           end;
       end;
 
@@ -1512,11 +1519,13 @@ implementation
                   RawRecord.WriteTo(FWriter);
                 end;
               PubDefRec.Free;
+              PubDefRec := nil;
             end;
 
         for i:=0 to Data.ObjSectionList.Count-1 do
           FreeAndNil(PubNamesForSection[i]);
         RawRecord.Free;
+        RawRecord := nil;
       end;
 
     procedure TOmfObjOutput.WriteEXTDEFs(Data: TObjData);
@@ -1552,10 +1561,13 @@ implementation
                 RawRecord.WriteTo(FWriter);
               end;
             ExtDefRec.Free;
+            ExtDefRec := nil;
           end;
 
         ExtNames.Free;
+        ExtNames := nil;
         RawRecord.Free;
+        RawRecord := nil;
       end;
 
     function TOmfObjOutput.writeData(Data:TObjData):boolean;
@@ -1595,6 +1607,7 @@ implementation
         Header.EncodeTo(RawRecord);
         RawRecord.WriteTo(FWriter);
         Header.Free;
+        Header := nil;
 
         { write translator COMENT header }
         Translator_COMENT:=TOmfRecord_COMENT.Create;
@@ -1604,6 +1617,7 @@ implementation
         Translator_COMENT.EncodeTo(RawRecord);
         RawRecord.WriteTo(FWriter);
         Translator_COMENT.Free;
+        Translator_COMENT := nil;
 
         if (target_dbg.id=dbg_codeview) or
            ((ds_dwarf_omf_linnum in current_settings.debugswitches) and
@@ -1615,6 +1629,7 @@ implementation
             DebugFormat_COMENT.EncodeTo(RawRecord);
             RawRecord.WriteTo(FWriter);
             DebugFormat_COMENT.Free;
+            DebugFormat_COMENT := nil;
           end;
 
         LNames.Clear;
@@ -1639,6 +1654,7 @@ implementation
             RawRecord.WriteTo(FWriter);
           end;
         LNamesRec.Free;
+        LNamesRec := nil;
 
         { write SEGDEF record(s) }
         for I:=1 to Segments.Count-1 do
@@ -1670,6 +1686,7 @@ implementation
         LinkPassSeparator_COMENT.EncodeTo(RawRecord);
         RawRecord.WriteTo(FWriter);
         LinkPassSeparator_COMENT.Free;
+        LinkPassSeparator_COMENT := nil;
 
         { write section content, interleaved with fixups }
         WriteSections(Data);
@@ -1679,8 +1696,10 @@ implementation
         ModEnd.EncodeTo(RawRecord);
         RawRecord.WriteTo(FWriter);
         ModEnd.Free;
+        ModEnd := nil;
 
         RawRecord.Free;
+        RawRecord := nil;
         result:=true;
       end;
 
@@ -1698,8 +1717,11 @@ implementation
     destructor TOmfObjOutput.Destroy;
       begin
         FGroups.Free;
+        FGroups := nil;
         FSegments.Free;
+        FSegments := nil;
         FLNames.Free;
+        FLNames := nil;
         inherited Destroy;
       end;
 
@@ -1718,6 +1740,7 @@ implementation
         Header.EncodeTo(RawRecord);
         RawRecord.WriteTo(FWriter);
         Header.Free;
+        Header := nil;
 
         { write IMPDEF record }
         DllImport_COMENT_IMPDEF:=TOmfRecord_COMENT_IMPDEF.Create;
@@ -1746,8 +1769,10 @@ implementation
         ModEnd.EncodeTo(RawRecord);
         RawRecord.WriteTo(FWriter);
         ModEnd.Free;
+        ModEnd := nil;
 
         RawRecord.Free;
+        RawRecord := nil;
       end;
 
 {****************************************************************************
@@ -1777,6 +1802,7 @@ implementation
         LNamesRec.Names:=LNames;
         LNamesRec.DecodeFrom(RawRec);
         LNamesRec.Free;
+        LNamesRec := nil;
         Result:=True;
       end;
 
@@ -1795,6 +1821,7 @@ implementation
           begin
             InputError('Segment name index out of range');
             SegDefRec.Free;
+            SegDefRec := nil;
             exit;
           end;
         SegmentName:=LNames[SegDefRec.SegmentNameIndex];
@@ -1802,6 +1829,7 @@ implementation
           begin
             InputError('Segment class name index out of range');
             SegDefRec.Free;
+            SegDefRec := nil;
             exit;
           end;
         SegClassName:=LNames[SegDefRec.ClassNameIndex];
@@ -1809,6 +1837,7 @@ implementation
           begin
             InputError('Segment overlay name index out of range');
             SegDefRec.Free;
+            SegDefRec := nil;
             exit;
           end;
         OverlayName:=LNames[SegDefRec.OverlayNameIndex];
@@ -1830,12 +1859,14 @@ implementation
             begin
               InputError('Absolute segment alignment not supported');
               SegDefRec.Free;
+              SegDefRec := nil;
               exit;
             end;
           saNotDefined:
             begin
               InputError('Invalid (unsupported/undefined) OMF segment alignment');
               SegDefRec.Free;
+              SegDefRec := nil;
               exit;
             end;
         end;
@@ -1861,6 +1892,7 @@ implementation
           begin
             InputError('Segment too large');
             SegDefRec.Free;
+            SegDefRec := nil;
             exit;
           end;
         objsec.Size:=SegDefRec.SegmentLength;
@@ -1872,6 +1904,7 @@ implementation
            (SegmentName='FPC') then
           objsec.SecOptions:=objsec.SecOptions+[oso_keep];
         SegDefRec.Free;
+        SegDefRec := nil;
         Result:=True;
       end;
 
@@ -1889,6 +1922,7 @@ implementation
           begin
             InputError('Group name index out of range');
             GrpDefRec.Free;
+            GrpDefRec := nil;
             exit;
           end;
         GroupName:=LNames[GrpDefRec.GroupNameIndex];
@@ -1903,11 +1937,13 @@ implementation
               begin
                 InputError('Segment name index out of range in group definition');
                 GrpDefRec.Free;
+                GrpDefRec := nil;
                 exit;
               end;
             SecGroup.members[i]:=TOmfObjSection(objdata.ObjSectionList[SegIndex-1]);
           end;
         GrpDefRec.Free;
+        GrpDefRec := nil;
         Result:=True;
       end;
 
@@ -1939,6 +1975,7 @@ implementation
             objsym.size:=0;
           end;
         ExtDefRec.Free;
+        ExtDefRec := nil;
         Result:=True;
       end;
 
@@ -1962,6 +1999,7 @@ implementation
           begin
             InputError('Public symbol''s group name index out of range');
             PubDefRec.Free;
+            PubDefRec := nil;
             exit;
           end;
         if PubDefRec.BaseGroupIndex<>0 then
@@ -1972,12 +2010,14 @@ implementation
           begin
             InputError('Public symbol''s segment name index out of range');
             PubDefRec.Free;
+            PubDefRec := nil;
             exit;
           end;
         if PubDefRec.BaseSegmentIndex=0 then
           begin
             InputError('Public symbol uses absolute addressing, which is not supported by this linker');
             PubDefRec.Free;
+            PubDefRec := nil;
             exit;
           end;
         objsec:=TOmfObjSection(objdata.ObjSectionList[PubDefRec.BaseSegmentIndex-1]);
@@ -2001,6 +2041,7 @@ implementation
               objsec.FFirstSym:=objsym;
           end;
         PubDefRec.Free;
+        PubDefRec := nil;
         Result:=True;
       end;
 
@@ -2020,18 +2061,21 @@ implementation
               begin
                 InputError('Physical start address not supported');
                 ModEndRec.Free;
+                ModEndRec := nil;
                 exit;
               end;
             if not (ModEndRec.TargetMethod in [ftmSegmentIndex,ftmSegmentIndexNoDisp]) then
               begin
                 InputError('Target method for start address other than "Segment Index" is not supported');
                 ModEndRec.Free;
+                ModEndRec := nil;
                 exit;
               end;
             if (ModEndRec.TargetDatum<1) or (ModEndRec.TargetDatum>objdata.ObjSectionList.Count) then
               begin
                 InputError('Segment name index for start address out of range');
                 ModEndRec.Free;
+                ModEndRec := nil;
                 exit;
               end;
             case ModEndRec.FrameMethod of
@@ -2041,12 +2085,14 @@ implementation
                     begin
                       InputError('Frame segment name index for start address out of range');
                       ModEndRec.Free;
+                      ModEndRec := nil;
                       exit;
                     end;
                   if ModEndRec.FrameDatum<>ModEndRec.TargetDatum then
                     begin
                       InputError('Frame segment different than target segment is not supported supported for start address');
                       ModEndRec.Free;
+                      ModEndRec := nil;
                       exit;
                     end;
                   basegroup:=nil;
@@ -2057,6 +2103,7 @@ implementation
                     begin
                       InputError('Frame group name index for start address out of range');
                       ModEndRec.Free;
+                      ModEndRec := nil;
                       exit;
                     end;
                   basegroup:=TObjSectionGroup(objdata.GroupsList[ModEndRec.FrameDatum-1]);
@@ -2065,6 +2112,7 @@ implementation
                 begin
                   InputError('Frame method for start address other than "Segment Index" or "Group Index" is not supported');
                   ModEndRec.Free;
+                  ModEndRec := nil;
                   exit;
                 end;
             end;
@@ -2079,6 +2127,7 @@ implementation
             objsym.size:=0;
           end;
         ModEndRec.Free;
+        ModEndRec := nil;
         Result:=True;
       end;
 
@@ -2176,6 +2225,7 @@ implementation
                   begin
                     InputError('Invalid checksum in OMF record');
                     FixupRawRec.Free;
+                    FixupRawRec := nil;
                     exit;
                   end;
               end;
@@ -2193,9 +2243,14 @@ implementation
                       begin
                         InputError('FIXUP subrecord without previous LEDATA or LIDATA record');
                         Fixup.Free;
+                        Fixup := nil;
                         Thread.Free;
+                        Thread := nil;
                         if FixupRawRec<>RawRec then
-                          FixupRawRec.Free;
+                          begin
+                            FixupRawRec.Free;
+                            FixupRawRec := nil;
+                          end;
                         exit;
                       end;
                     NextOfs:=Fixup.ReadAt(FixupRawRec,NextOfs);
@@ -2210,7 +2265,9 @@ implementation
                   end;
               end;
             Fixup.Free;
+            Fixup := nil;
             Thread.Free;
+            Thread := nil;
             if FixupRawRec<>RawRec then
               FixupRawRec.Free;
             { always set it to null, so that we read the next record on the next }
@@ -2237,6 +2294,7 @@ implementation
           TOmfObjData(objdata).AddImportSymbol(MaybeAddDllExt(ImpDefRec.ModuleName),ImpDefRec.Name,SymName,0,false);
         Result:=True;
         ImpDefRec.Free;
+        ImpDefRec := nil;
       end;
 
     function TOmfObjInput.ReadExpDef(Rec: TOmfRecord_COMENT; objdata: TObjData): Boolean;
@@ -2259,6 +2317,7 @@ implementation
           ExpDefRec.ExportOrdinal);
         Result:=True;
         ExpDefRec.Free;
+        ExpDefRec := nil;
       end;
 
     function TOmfObjInput.ImportOmfFixup(objdata: TObjData; objsec: TOmfObjSection; Fixup: TOmfSubRecord_FIXUP): Boolean;
@@ -2571,11 +2630,17 @@ implementation
     destructor TOmfObjInput.destroy;
       begin
         FCOMENTRecord.Free;
+        FCOMENTRecord := nil;
         FRawRecord.Free;
+        FRawRecord := nil;
         FFixupThreads.Free;
+        FFixupThreads := nil;
         FPubDefs.Free;
+        FPubDefs := nil;
         FExtDefs.Free;
+        FExtDefs := nil;
         FLNames.Free;
+        FLNames := nil;
         inherited destroy;
       end;
 
@@ -2832,6 +2897,7 @@ implementation
     destructor TMZExeUnifiedLogicalSegment.destroy;
       begin
         FObjSectionList.Free;
+        FObjSectionList := nil;
         inherited destroy;
       end;
 
@@ -2885,6 +2951,7 @@ implementation
     destructor TMZExeUnifiedLogicalGroup.destroy;
       begin
         FSegmentList.Free;
+        FSegmentList := nil;
         inherited destroy;
       end;
 
@@ -3434,6 +3501,7 @@ implementation
         Result:=True;
 cleanup:
         shstrtabsect_data.Free;
+        shstrtabsect_data := nil;
       end;
 
     procedure TMZExeOutput.Load_Symbol(const aname: string);
@@ -3772,9 +3840,13 @@ cleanup:
     destructor TMZExeOutput.destroy;
       begin
         FHeader.Free;
+        FHeader := nil;
         FDwarfUnifiedLogicalSegments.Free;
+        FDwarfUnifiedLogicalSegments := nil;
         FExeUnifiedLogicalGroups.Free;
+        FExeUnifiedLogicalGroups := nil;
         FExeUnifiedLogicalSegments.Free;
+        FExeUnifiedLogicalSegments := nil;
         inherited destroy;
       end;
 
@@ -4270,6 +4342,7 @@ cleanup:
     destructor TNewExeRelocationList.Destroy;
       begin
         FInternalList.Free;
+        FInternalList := nil;
         inherited Destroy;
       end;
 
@@ -4322,6 +4395,7 @@ cleanup:
     destructor TNewExeSection.destroy;
       begin
         FRelocations.Free;
+        FRelocations := nil;
         inherited destroy;
       end;
 
@@ -4707,12 +4781,19 @@ cleanup:
     destructor TNewExeOutput.destroy;
       begin
         FEntryTable.Free;
+        FEntryTable := nil;
         FImportedNameTable.Free;
+        FImportedNameTable := nil;
         FModuleReferenceTable.Free;
+        FModuleReferenceTable := nil;
         FNonresidentNameTable.Free;
+        FNonresidentNameTable := nil;
         FResidentNameTable.Free;
+        FResidentNameTable := nil;
         FResourceTable.Free;
+        FResourceTable := nil;
         FHeader.Free;
+        FHeader := nil;
         inherited destroy;
       end;
 
@@ -4771,6 +4852,7 @@ cleanup:
             CurrExeSec.AddObjSection(objsec);
           end;
         TmpObjSectionList.Free;
+        TmpObjSectionList := nil;
       end;
 
     procedure TNewExeOutput.MemPos_Start;

+ 1 - 0
compiler/ogrel.pas

@@ -1230,6 +1230,7 @@ implementation
                 end;
             end;
         instance.Free;
+        instance := nil;
       end;
 
 

+ 25 - 7
compiler/ogwasm.pas

@@ -27,7 +27,7 @@ interface
 
     uses
       { common }
-      cclasses,globtype,
+      sysutils,cclasses,globtype,
       { target }
       systems,cpubase,
       { assembler }
@@ -699,6 +699,7 @@ implementation
     destructor TWasmObjSymbolLinkingData.Destroy;
       begin
         FuncType.Free;
+        FuncType := nil;
         inherited Destroy;
       end;
 
@@ -735,6 +736,7 @@ implementation
     destructor TWasmObjRelocation.Destroy;
       begin
         FuncType.Free;
+        FuncType := nil;
         inherited Destroy;
       end;
 
@@ -771,6 +773,7 @@ implementation
     destructor TWasmObjSymbol.Destroy;
       begin
         LinkingData.Free;
+        LinkingData := nil;
         inherited Destroy;
       end;
 
@@ -794,6 +797,7 @@ implementation
     destructor TWasmObjSymbolExtraData.Destroy;
       begin
         EncodedLocals.Free;
+        EncodedLocals := nil;
         inherited Destroy;
       end;
 
@@ -1076,7 +1080,9 @@ implementation
         i: Integer;
       begin
         FObjSymbolsExtraDataList.Free;
+        FObjSymbolsExtraDataList := nil;
         FFuncTypes.Free;
+        FFuncTypes := nil;
         inherited destroy;
       end;
 
@@ -1277,6 +1283,7 @@ implementation
         ft:=TWasmFuncType.Create([],tt.params);
         i:=FFuncTypes.AddOrGetFuncType(ft);
         ft.free;
+        ft := nil;
         ObjSymExtraData.ExceptionTagTypeIdx:=i;
       end;
 
@@ -2460,21 +2467,31 @@ implementation
         k: TWasmLinkingSubsectionType;
       begin
         for i in TWasmSectionID do
-          FWasmSections[i].Free;
+          FreeAndNil(FWasmSections[i]);
         for j in TWasmCustomSectionType do
-          FWasmCustomSections[j].Free;
+          FreeAndNil(FWasmCustomSections[j]);
         for k:=low(TWasmLinkingSubsectionType) to high(TWasmLinkingSubsectionType) do
-          FWasmLinkingSubsections[k].Free;
+          FreeAndNil(FWasmLinkingSubsections[k]);
         FWasmSymbolTable.Free;
+        FWasmSymbolTable := nil;
         FWasmRelocationCodeTable.Free;
+        FWasmRelocationCodeTable := nil;
         FWasmRelocationDataTable.Free;
+        FWasmRelocationDataTable := nil;
         FWasmRelocationDebugFrameTable.Free;
+        FWasmRelocationDebugFrameTable := nil;
         FWasmRelocationDebugInfoTable.Free;
+        FWasmRelocationDebugInfoTable := nil;
         FWasmRelocationDebugLineTable.Free;
+        FWasmRelocationDebugLineTable := nil;
         FWasmRelocationDebugAbbrevTable.Free;
+        FWasmRelocationDebugAbbrevTable := nil;
         FWasmRelocationDebugArangesTable.Free;
+        FWasmRelocationDebugArangesTable := nil;
         FWasmRelocationDebugRangesTable.Free;
+        FWasmRelocationDebugRangesTable := nil;
         FWasmRelocationDebugStrTable.Free;
+        FWasmRelocationDebugStrTable := nil;
         inherited destroy;
       end;
 
@@ -5571,12 +5588,13 @@ implementation
         k: TWasmNameSubsectionType;
       begin
         for i in TWasmSectionID do
-          FWasmSections[i].Free;
+          FreeAndNil(FWasmSections[i]);
         for j in TWasmCustomSectionType do
-          FWasmCustomSections[j].Free;
+          FreeAndNil(FWasmCustomSections[j]);
         for k:=low(FWasmNameSubsections) to high(FWasmNameSubsections) do
-          FWasmNameSubsections[k].Free;
+          FreeAndNil(FWasmNameSubsections[k]);
         FFuncTypes.Free;
+        FFuncTypes := nil;
         inherited destroy;
       end;
 

+ 3 - 2
compiler/omfbase.pas

@@ -2396,6 +2396,7 @@ implementation
   destructor TOmfSubRecord_LINNUM_MsLink_LineNumberList.Destroy;
     begin
       FLineNumbers.Free;
+      FLineNumbers := nil;
       inherited Destroy;
     end;
 
@@ -2515,8 +2516,8 @@ implementation
     begin
       for t in TOmfFixupThread do
         begin
-          FTargetThreads[t].Free;
-          FFrameThreads[t].Free;
+          FreeAndNil(FTargetThreads[t]);
+          FreeAndNil(FFrameThreads[t]);
         end;
       inherited Destroy;
     end;

+ 1 - 0
compiler/optconstprop.pas

@@ -240,6 +240,7 @@ unit optconstprop;
                     n:=tinlinenode(n).getaddsub_for_incdec;
                     Include(n.flags, nf_internal);
                     oldnode.free;
+                    oldnode := nil;
                     tree_modified:=true;
                     { do not continue, value changed, if further const. propagations are possible, this is done
                       by the next pass }

+ 7 - 6
compiler/optcse.pas

@@ -29,7 +29,7 @@ unit optcse;
   interface
 
     uses
-      node;
+      sysutils,node;
 
     {
       the function  creates non optimal code so far:
@@ -523,16 +523,17 @@ unit optcse;
                 { clean up unused trees }
                 for i:=0 to lists.nodelist.count-1 do
                   if lists.equalto[i]<>pointer(-1) then
-                    tnode(lists.nodelist[i]).free;
+                    tnode(lists.nodelist[i]).free; // no nil needed
 {$ifdef csedebug}
                 writeln('nodes: ',lists.nodelist.count);
                 writeln('==========================================');
 {$endif csedebug}
-                lists.nodelist.free;
-                lists.locationlist.free;
-                lists.equalto.free;
-                lists.refs.free;
+                FreeAndNil(lists.nodelist);
+                FreeAndNil(lists.locationlist);
+                FreeAndNil(lists.equalto);
+                FreeAndNil(lists.refs);
                 templist.free;
+                templist := nil;
 
                 if assigned(statements) then
                   begin

+ 2 - 0
compiler/optdfa.pas

@@ -672,7 +672,9 @@ unit optdfa;
     destructor TDFABuilder.Destroy;
       begin
         Resultnode.free;
+        Resultnode := nil;
         nodemap.free;
+        nodemap := nil;
         inherited destroy;
       end;
 

+ 11 - 0
compiler/options.pas

@@ -2355,14 +2355,23 @@ end;
 destructor TOption.Destroy;
 begin
   ParaIncludeCfgPath.Free;
+  ParaIncludeCfgPath := nil;
   ParaIncludePath.Free;
+  ParaIncludePath := nil;
   ParaObjectPath.Free;
+  ParaObjectPath := nil;
   ParaUnitPath.Free;
+  ParaUnitPath := nil;
   ParaLibraryPath.Free;
+  ParaLibraryPath := nil;
   ParaFrameworkPath.Free;
+  ParaFrameworkPath := nil;
   parapackagepath.Free;
+  parapackagepath := nil;
   ParaPackages.Free;
+  ParaPackages := nil;
   paranamespaces.free;
+  paranamespaces := nil;
 end;
 
 procedure TOption.Interpret_A_l(opt, more: TCmdStr);
@@ -5156,6 +5165,7 @@ begin
       cmditem:=TCmdStrListItem(cmditem.Next);
     end;
   tmplist.Free;
+  tmplist := nil;
 
   { add unit environment and exepath to the unit search path }
   if inputfilepath<>'' then
@@ -6012,4 +6022,5 @@ initialization
 finalization
   if assigned(option) then
    option.free;
+   option := nil;
 end.

+ 1 - 0
compiler/optloop.pas

@@ -606,6 +606,7 @@ unit optloop;
 
             n:=internalstatements(newcodestatements);
             oldn.Free;
+            oldn := nil;
             addstatement(newcodestatements,initcode);
             addstatement(newcodestatements,newfor);
             addstatement(newcodestatements,deletecode);

+ 2 - 0
compiler/opttail.pas

@@ -217,6 +217,7 @@ unit opttail;
                       end;
 
                     oldnodetree.free;
+                    oldnodetree := nil;
 
                     do_firstpass(n);
                     result:=true;
@@ -298,6 +299,7 @@ unit opttail;
           end
         else
           labelnode.free;
+          labelnode := nil;
       end;
 
 end.

+ 6 - 0
compiler/owar.pas

@@ -182,9 +182,13 @@ implementation
         if Errorcount=0 then
          writear;
         arData.Free;
+        arData := nil;
         symreloc.Free;
+        symreloc := nil;
         symstr.Free;
+        symstr := nil;
         lfnstr.Free;
+        lfnstr := nil;
       end;
 
 
@@ -320,6 +324,7 @@ implementation
          end;
         ardata.WriteStream(arf);
         Arf.Free;
+        Arf := nil;
       end;
 
 
@@ -354,6 +359,7 @@ implementation
       begin
         inherited closefile;
         ArSymbols.Free;
+        ArSymbols := nil;
         LFNStrs:=nil;
         inherited Destroy;
       end;

+ 2 - 0
compiler/owbase.pas

@@ -151,6 +151,7 @@ begin
    writebuf;
   fn:=f.filename;
   f.free;
+  f := nil;
 { Remove if size is 0 }
   if size=0 then
    DeleteFile(fn);
@@ -282,6 +283,7 @@ begin
   setlength(buf,bufmax);
   f.read(buf[0],bufmax);
   f.free;
+  f := nil;
   bufidx:=0;
   opened:=true;
   openfile:=true;

+ 17 - 0
compiler/owomflib.pas

@@ -166,6 +166,7 @@ implementation
     destructor TOmfLibObjectWriter.TOmfLibObjectModule.Destroy;
       begin
         FObjData.Free;
+        FObjData := nil;
         inherited Destroy;
       end;
 
@@ -205,8 +206,11 @@ implementation
         if Errorcount=0 then
           WriteLib;
         FLibData.Free;
+        FLibData := nil;
         FObjectModules.Free;
+        FObjectModules := nil;
         FDictionary.Free;
+        FDictionary := nil;
         inherited destroy;
       end;
 
@@ -231,6 +235,7 @@ implementation
         if RawRec.RecordType<>RT_THEADR then
           begin
             RawRec.Free;
+            RawRec := nil;
             InternalError(2018060801);
           end;
         ObjHeader:=TOmfRecord_THEADR.Create;
@@ -238,7 +243,9 @@ implementation
         { create a dictionary entry with the module name }
         TOmfLibDictionaryEntry.Create(FDictionary,ModName2DictEntry(ObjHeader.ModuleName),FCurrentModuleIndex);
         ObjHeader.Free;
+        ObjHeader := nil;
         RawRec.Free;
+        RawRec := nil;
         fobjsize:=0;
       end;
 
@@ -274,7 +281,9 @@ implementation
         FLibData.seek(0);
         RawRec.WriteTo(FLibData);
         Header.Free;
+        Header := nil;
         RawRec.Free;
+        RawRec := nil;
       end;
 
     procedure TOmfLibObjectWriter.WriteFooter;
@@ -289,7 +298,9 @@ implementation
         Footer.EncodeTo(RawRec);
         RawRec.WriteTo(FLibData);
         Footer.Free;
+        Footer := nil;
         RawRec.Free;
+        RawRec := nil;
       end;
 
     function TOmfLibObjectWriter.TryPageSize(aPageSize: Integer): Boolean;
@@ -365,6 +376,7 @@ implementation
         WriteHeader(DictStart,DictBlocks);
         FLibData.WriteStream(libf);
         libf.Free;
+        libf := nil;
       end;
 
     function TOmfLibObjectWriter.WriteDictionary: Word;
@@ -484,7 +496,9 @@ implementation
       FIsCaseSensitive:=Header.CaseSensitive;
       ReadDictionary(Header.DictionaryOffset, Header.DictionarySizeInBlocks);
       Header.Free;
+      Header := nil;
       RawRecord.Free;
+      RawRecord := nil;
     end;
 
   procedure TOmfLibObjectReader.ReadDictionary(DictionaryOffset: DWord; DictionarySizeInBlocks: Word);
@@ -571,6 +585,7 @@ implementation
     begin
       inherited closefile;
       LibSymbols.Free;
+      LibSymbols := nil;
       inherited Destroy;
     end;
 
@@ -594,7 +609,9 @@ implementation
       Header.DecodeFrom(RawRec);
       CurrMemberName:=Header.ModuleName;
       Header.Free;
+      Header := nil;
       RawRec.Free;
+      RawRec := nil;
 
       { go back to the beginning of the file }
       inherited Seek(CurrMemberPos);

+ 1 - 0
compiler/paramgr.pas

@@ -868,4 +868,5 @@ initialization
   ;
 finalization
   paramanager.free;
+  paramanager := nil;
 end.

+ 8 - 2
compiler/parser.pas

@@ -101,6 +101,7 @@ implementation
               begin
                 loaded_units.remove(hp);
                 hp.free;
+                hp := nil;
               end;
             hp:=hp2;
           end;
@@ -294,22 +295,25 @@ implementation
            still assinged }
          if assigned(current_scanner) then
           begin
-            current_scanner.free;
+            current_scanner.free; // no nil needed
             set_current_scanner(nil);
-
           end;
 
          { close scanner }
          DoneScanner;
 
          RTTIWriter.free;
+         RTTIWriter := nil;
 
          { close ppas,deffile }
          asmres.free;
+         asmres := nil;
          deffile.free;
+         deffile := nil;
 
          { free list of .o files }
          SmartLinkOFiles.Free;
+         SmartLinkOFiles := nil;
       end;
 
 
@@ -388,9 +392,11 @@ implementation
          until false;
        { free scanner }
          current_scanner.free;
+         current_scanner := nil;
          set_current_scanner(nil);
        { close }
          preprocfile.free;
+         preprocfile := nil;
       end;
 {$endif PREPROCWRITE}
 

+ 1 - 0
compiler/pass_1.pas

@@ -246,6 +246,7 @@ implementation
         aktstate:=Tstate_storage.create;
         p.track_state_pass(true);
             aktstate.free;
+            aktstate := nil;
      end;
 {$endif}
 

+ 13 - 5
compiler/pdecl.pas

@@ -210,6 +210,7 @@ implementation
           end;
         current_tokenpos:=storetokenpos;
         p.free;
+        p := nil;
         readconstant:=hp;
       end;
 
@@ -484,7 +485,7 @@ implementation
               if not is_system_custom_attribute_descendant(od) then
                 begin
                   incompatibletypes(od,class_tcustomattribute);
-                  read_attr_paras.free;
+                  read_attr_paras.free; // no nil needed
                   continue;
                 end;
 
@@ -555,8 +556,9 @@ implementation
                     begin
                       { cleanup }
                       pcalln.free;
+                      pcalln := nil;
                       for i:=0 to high(paras) do
-                        paras[i].free;
+                        FreeAndNil(paras[i]);
                     end;
                 end
               else begin
@@ -564,16 +566,18 @@ implementation
                 if errorcount=ecnt then
                   message(parser_e_illegal_expression);
                 pcalln.free;
+                pcalln := nil;
               end;
             end
           else
             begin
               Message(type_e_type_id_expected);
               { try to recover by nevertheless reading the parameters (if any) }
-              read_attr_paras.free;
+              read_attr_paras.free; // no nil needed
             end;
 
           p.free;
+          p := nil;
         until not try_to_consume(_COMMA);
 
         consume(_RECKKLAMMER);
@@ -949,6 +953,7 @@ implementation
                                   tstringdef(hdef).encoding:=int64(tordconstnode(p).value);
                                 end;
                               p.free;
+                              p := nil;
                             end;
                           if (hdef.typ in [pointerdef,classrefdef]) and
                              (tabstractpointerdef(hdef).pointeddef.typ=forwarddef) then
@@ -1205,11 +1210,12 @@ implementation
                  begin
                    if (tstoredsym(generictypelist[i]).typ=typesym) and
                        not ttypesym(generictypelist[i]).typedef.is_registered then
-                     ttypesym(generictypelist[i]).typedef.free;
+                     FreeAndNil(ttypesym(generictypelist[i]).typedef);
                    if not tstoredsym(generictypelist[i]).is_registered then
-                     tstoredsym(generictypelist[i]).free;
+                     tstoredsym(generictypelist[i]).free; // no nil needed
                  end;
                generictypelist.free;
+               generictypelist := nil;
              end;
 
            if not (m_delphi in current_settings.modeswitches) and
@@ -1254,6 +1260,7 @@ implementation
         rtti_attrs_def := nil;
         types_dec(false,had_generic,rtti_attrs_def);
         rtti_attrs_def.free;
+        rtti_attrs_def := nil;
       end;
 
 
@@ -1402,6 +1409,7 @@ implementation
                      stringdispose(deprecatedmsg);
                    consume(_SEMICOLON);
                    p.free;
+                   p := nil;
                 end;
               else
                 if not first and isgeneric and

+ 3 - 0
compiler/pdecobj.pas

@@ -423,6 +423,7 @@ implementation
         else
           Message(parser_e_illegal_expression);
         p.free;
+        p := nil;
       end;
 
     procedure get_cpp_or_java_class_external_status(od: tobjectdef);
@@ -1403,6 +1404,7 @@ implementation
                                     trtti_attribute_list.bind(rtti_attrs_def,tfieldvarsym(fieldlist[FldCount]).rtti_attribute_list)
                                   else
                                     rtti_attrs_def.free;
+                                    rtti_attrs_def := nil;
                                   end;
                                 rtti_attrs_def:=nil;
                               end;
@@ -1477,6 +1479,7 @@ implementation
         if is_class(current_structdef) then
           tabstractrecordsymtable(current_structdef.symtable).addfieldlist(fieldlist,true);
         fieldlist.free;
+        fieldlist := nil;
       end;
 
 

+ 5 - 1
compiler/pdecsub.pas

@@ -334,7 +334,7 @@ implementation
             if assigned(vs.owner) then
              sc.add(vs)
             else
-             vs.free;
+             vs.free; // no nil needed
             consume(_ID);
           until not try_to_consume(_COMMA);
           locationstr:='';
@@ -528,6 +528,7 @@ implementation
 
         { remove parasymtable from stack }
         sc.free;
+        sc := nil;
         { reset object options }
         block_type:=old_block_type;
         consume(_RKLAMMER);
@@ -647,6 +648,7 @@ implementation
                       sym.typedef:=nil;
                     end;
                   sym.free;
+                  sym := nil;
                 end;
             genericparams.free;
             genericparams:=nil;
@@ -2091,6 +2093,7 @@ begin
   else
     message(parser_e_dispid_must_be_ord_const);
   pt.free;
+  pt := nil;
 end;
 
 
@@ -2201,6 +2204,7 @@ begin
      not objcvalidselectorname(@tprocdef(pd).messageinf.str^[1],length(tprocdef(pd).messageinf.str^)) then
     Message1(type_e_invalid_objc_selector_name,tprocdef(pd).messageinf.str^);
   pt.free;
+  pt := nil;
 end;
 
 

+ 17 - 5
compiler/pdecvar.pas

@@ -200,6 +200,7 @@ implementation
                              end;
                             pl.addconst(sl_vec,idx,p.resultdef);
                             p.free;
+                            p := nil;
                             def:=tarraydef(def).elementdef;
                           end
                          else
@@ -306,6 +307,7 @@ implementation
                   else
                     Message(parser_e_dispid_must_be_ord_const);
                   pt.free;
+                  pt := nil;
                 end
               else
                 hdispid:=tobjectdef(astruct).get_next_dispid;
@@ -435,6 +437,7 @@ implementation
                   tparavarsym(sc[i]).vardef:=hdef;
               until not try_to_consume(_SEMICOLON);
               sc.free;
+              sc := nil;
               symtablestack.pop(p.parast);
               consume(_RECKKLAMMER);
 
@@ -492,6 +495,7 @@ implementation
                    { concat a longint to the para templates }
                    p.add_index_parameter(paranr,readprocdef,writeprocdef);
                    pt.free;
+                   pt := nil;
                 end;
            end
          else
@@ -704,6 +708,7 @@ implementation
                   { Error recovery }
                   pt:=comp_expr([ef_accept_equal]);
                   pt.free;
+                  pt := nil;
                 end
               else
                 begin
@@ -737,6 +742,7 @@ implementation
                       internalerror(2019050525);
                   end;
                   pt.free;
+                  pt := nil;
                 end;
            end
          else if not is_record(astruct) and try_to_consume(_NODEFAULT) then
@@ -870,22 +876,22 @@ implementation
              if readprocdef.proctypeoption=potype_propgetter then
                readprocdef.register_def
              else
-               readprocdef.free;
+               readprocdef.free; // no nil needed
              if writeprocdef.proctypeoption=potype_propsetter then
                writeprocdef.register_def
              else
-               writeprocdef.free;
+               writeprocdef.free; // no nil needed
            end
          else
            begin
              if readprocdef.proctypeoption=potype_propgetter then
                readprocdef.maybe_put_in_symtable_stack
              else
-               readprocdef.free;
+               readprocdef.free; // no nil needed
              if writeprocdef.proctypeoption=potype_propsetter then
                writeprocdef.maybe_put_in_symtable_stack
              else
-               writeprocdef.free;
+               writeprocdef.free; // no nil needed
            end;
 
          result:=p;
@@ -1152,6 +1158,7 @@ implementation
                     current_asmdata.asmlists[al_typedconsts].concatlist(templist);
                   end;
                 templist.free;
+                templist := nil;
               end;
             staticvarsym :
               begin
@@ -1338,6 +1345,7 @@ implementation
                 Message(parser_e_absolute_only_to_var_or_const);
             end;
           pt.free;
+          pt := nil;
           { replace old varsym with the new absolutevarsym }
           if assigned(abssym) then
             begin
@@ -1419,6 +1427,7 @@ implementation
                    and (token in [_PROCEDURE,_FUNCTION,_CLASS]) then
                  begin
                    vs.free;
+                   vs := nil;
                    sc.clear;
                    had_generic:=true;
                    break;
@@ -1635,6 +1644,7 @@ implementation
          block_type:=old_block_type;
          { free the list }
          sc.free;
+         sc := nil;
       end;
 
 
@@ -1768,7 +1778,7 @@ implementation
                    had_generic:=false;
                  end
                else
-                 vs.free;
+                 vs.free; // no nil needed
              until not try_to_consume(_COMMA);
              if m_delphi in current_settings.modeswitches then
                block_type:=bt_var_type
@@ -2063,6 +2073,7 @@ implementation
                         end;
                     end;
                   pt.free;
+                  pt := nil;
                   if token=_COMMA then
                     consume(_COMMA)
                   else
@@ -2138,6 +2149,7 @@ implementation
            end;
          { free the list }
          sc.free;
+         sc := nil;
 {$ifdef powerpc}
          is_first_type := false;
 {$endif powerpc}

+ 2 - 0
compiler/pexports.pas

@@ -153,6 +153,7 @@ implementation
                         end;
                        include(options,eo_index);
                        pt.free;
+                       pt := nil;
                        if target_info.system in [system_i386_win32,system_i386_wdosx,system_arm_wince,system_i386_wince] then
                         DefString:=srsym.realname+'='+InternalProcName+' @ '+tostr(index)
                        else
@@ -169,6 +170,7 @@ implementation
                          message(type_e_string_expr_expected);
                        include(options,eo_name);
                        pt.free;
+                       pt := nil;
                        DefString:=hpname+'='+InternalProcName;
                      end;
                     if try_to_consume(_RESIDENT) then

+ 26 - 5
compiler/pexpr.pas

@@ -138,6 +138,7 @@ implementation
                 consume(_RECKKLAMMER);
               end;
              p.free;
+             p := nil;
            end
           else
             begin
@@ -424,6 +425,7 @@ implementation
                begin
                  Message(parser_e_class_id_expected);
                  p1.free;
+                 p1 := nil;
                  statement_syssym:=cerrornode.create;
                end;
             end;
@@ -482,6 +484,7 @@ implementation
                     include(statement_syssym.flags,nf_generic_para);
                  { p1 not needed !}
                  p1.free;
+                 p1 := nil;
                end;
             end;
 
@@ -605,6 +608,7 @@ implementation
               else
                begin
                  p1.free;
+                 p1 := nil;
                  p2:=cerrornode.create;
                end;
               consume(_RKLAMMER);
@@ -718,9 +722,9 @@ implementation
                   message(parser_e_illegal_slice);
                   consume(_LKLAMMER);
                   in_args:=true;
-                  comp_expr([ef_accept_equal]).free;
+                  comp_expr([ef_accept_equal]).free; // no nil needed
                   if try_to_consume(_COMMA) then
-                    comp_expr([ef_accept_equal]).free;
+                    comp_expr([ef_accept_equal]).free; // no nil needed
                   statement_syssym:=cerrornode.create;
                   consume(_RKLAMMER);
                 end
@@ -903,6 +907,7 @@ implementation
                   in_args:=true;
                   p1:=comp_expr([ef_accept_equal]);
                   p1.free;
+                  p1 := nil;
                   consume(_RKLAMMER);
                 end;
               statement_syssym:=geninlinenode(l,false,nil);
@@ -1108,6 +1113,7 @@ implementation
                  comment(v_error, 'Pointers to generics functions not implemented');
                  p1:=cerrornode.create;
                  spezcontext.free;
+                 spezcontext := nil;
                  exit;
                end;
 
@@ -1161,7 +1167,7 @@ implementation
                         this is a "objectprocvar:[email protected]" expression }
                       tloadnode(p2).symtable:=tobjectdef(p1.resultdef).symtable
                     else
-                      p1.free;
+                      p1.free; // no nil needed
                   end;
               end;
              p1:=p2;
@@ -1254,6 +1260,7 @@ implementation
                  if (po_methodpointer in pv.procoptions) then
                    tloadnode(hp2).set_mp(tcallnode(hp).methodpointer.getcopy);
                  hp.free;
+                 hp := nil;
                  { replace the old callnode with the new loadnode }
                  hpp^:=hp2;
                end;
@@ -1293,6 +1300,7 @@ implementation
                begin
                  hp2:=cloadnode.create_procvar(tprocsym(tcallnode(hp).symtableprocentry),currprocdef,tcallnode(hp).symtableproc);
                  hp.free;
+                 hp := nil;
                  { replace the old callnode with the new loadnode }
                  hpp^:=hp2;
                end;
@@ -1440,7 +1448,7 @@ implementation
            end;
         { release paras if not used }
         if assigned(paras) then
-         paras.free;
+          paras.free; // no nil needed
       end;
 
 
@@ -1461,6 +1469,7 @@ implementation
               p1:=cerrornode.create;
               { try to clean up }
               spezcontext.free;
+              spezcontext := nil;
               again:=false;
            end
          else
@@ -1793,8 +1802,10 @@ implementation
                    end;
                  if result.nodetype<>errorn then
                    do_member_read(tabstractrecorddef(hdef),false,srsym,result,again,[],spezcontext)
-                 else
+                 else begin
                    spezcontext.free;
+                   spezcontext := nil;
+                 end;
                end
              else
               begin
@@ -2028,6 +2039,7 @@ implementation
            end;
          countindices:=elements.count;
          elements.free;
+         elements := nil;
 
          consume(_RECKKLAMMER);
 
@@ -3130,6 +3142,7 @@ implementation
                          if not handle_specialize_inline_specialization(srsym,unit_found,srsymtable,spezcontext) or (srsym.typ=procsym) then
                            begin
                              spezcontext.free;
+                             spezcontext := nil;
                              result:=cerrornode.create;
                              if try_to_consume(_LKLAMMER) then
                               begin
@@ -3292,6 +3305,7 @@ implementation
               result.resultdef:=cundefineddef.create(true);
               { clean up previously created dummy symbol }
               srsym.free;
+              srsym := nil;
             end;
 
           errorsym :
@@ -3987,7 +4001,10 @@ implementation
                            do_member_read(hclassdef,getaddr,srsym,p1,again,callflags,spezcontext);
                          end;
                        if p1.nodetype=errorn then
+                       begin
                          spezcontext.free;
+                         spezcontext := nil;
+                       end;
                      end
                     else
                      begin
@@ -4645,6 +4662,7 @@ implementation
               result:=cerrornode.create;
 
           spezcontext.free;
+          spezcontext := nil;
         end;
 
       function maybe_handle_specialization(var p1,p2:tnode;filepos:tfileposinfo):boolean;
@@ -4687,6 +4705,7 @@ implementation
               { we don't need these nodes anymore }
               p1.free;
               p2.free;
+              p2 := nil;
 
               p1:=ptmp;
 
@@ -5073,6 +5092,7 @@ implementation
           result:=tordconstnode(p).value;
        end;
       p.free;
+      p := nil;
     end;
 
 
@@ -5110,6 +5130,7 @@ implementation
       else
         get_stringconst:=snode.asrawbytestring;
       p.free;
+      p := nil;
     end;
 
 end.

+ 1 - 0
compiler/pgentype.pas

@@ -72,6 +72,7 @@ end;
 destructor tspecializationcontext.destroy;
 begin
   paramlist.free;
+  paramlist := nil;
   tfplist.FreeAndNilDisposing(poslist,TypeInfo(tfileposinfo));
   inherited destroy;
 end;

+ 26 - 3
compiler/pgenutil.pas

@@ -646,6 +646,7 @@ uses
                 result:=false;
               end;
             typeparam.free;
+            typeparam := nil;
             first:=false;
           end;
         block_type:=old_block_type;
@@ -673,7 +674,7 @@ uses
           genericdef:=tstoreddef(generate_specialization_phase2(context,genericdef,parse_class_parent,_prettyname));
         tt:=genericdef;
         if assigned(context) then
-          context.free;
+          context.free; // no nil needed
       end;
 
 
@@ -1033,6 +1034,7 @@ uses
               if compare_defs(caller_proc_para.vardef,target_proc_para.vardef,nothingn)=te_incompatible then
                 begin
                   newparams.free;
+                  newparams := nil;
                   exit(false);
                 end;
 
@@ -1055,6 +1057,7 @@ uses
               if compare_defs(caller_proc.returndef,target_proc.returndef,nothingn)<te_equal then
                 begin
                   newparams.free;
+                  newparams := nil;
                   exit(false);
                 end;
 
@@ -1072,6 +1075,7 @@ uses
               genericparams.add(newparams.nameofindex(i),newparams[i]);
 
           newparams.free;
+          newparams := nil;
         end;
 
       function maybe_inherited_specialization(givendef,desireddef:tstoreddef;out basedef:tstoreddef):boolean;
@@ -1147,6 +1151,7 @@ uses
           if callerparams.count<required_param_count then
             begin
               paras.free;
+              paras := nil;
               exit;
             end;
 
@@ -1160,6 +1165,7 @@ uses
           if count<genericdef.genericparas.count then
             begin
               paras.free;
+              paras := nil;
               exit;
             end;
 
@@ -1172,7 +1178,9 @@ uses
               if i=paras.count then
                 begin
                   genericparams.free;
+                  genericparams := nil;
                   paras.free;
+                  paras := nil;
                   exit;
                 end;
 
@@ -1261,8 +1269,11 @@ uses
 
           { cleanup }
           paras.free;
-          if not result then
+          paras := nil;
+          if not result then begin
             genericparams.free;
+            genericparams := nil;
+          end;
         end;
 
       { make an ordered list of parameters from the caller }
@@ -1323,10 +1334,12 @@ uses
                   begin
                     generate_implicit_specialization(spezcontext,pd,genericparams);
                     genericparams.free;
+                    genericparams := nil;
                     { finalize the specialization so it can be added to the list of overloads }
                     if not finalize_specialization(pd,spezcontext) then
                       begin
                         spezcontext.free;
+                        spezcontext := nil;
                         continue;
                       end;
                     { handle unnamed syms used by the specialization }
@@ -1334,9 +1347,11 @@ uses
                       begin
                         transfer_unnamed_symbols(pd.owner,pd_unnamed_syms);
                         pd_unnamed_syms.free;
+                        pd_unnamed_syms := nil;
                       end;
                     pdoverloadlist.add(pd);
                     spezcontext.free;
+                    spezcontext := nil;
                     if po_overload in pd.procoptions then
                       hasoverload:=true;
                     { store first procsym found }
@@ -1363,6 +1378,7 @@ uses
           end;
 
         callerparams.free;
+        callerparams := nil;
       end;
 
     function generate_specialization_phase1(out context:tspecializationcontext;genericdef:tdef;enforce_unit:boolean):tdef;
@@ -1558,6 +1574,7 @@ uses
             for i:=tmpstack.count-1 downto 0 do
               symtablestack.push(tsymtable(tmpstack[i]));
             tmpstack.free;
+            tmpstack := nil;
           end;
 
         if not found or not (context.sym.typ in [typesym,procsym]) then
@@ -2196,6 +2213,7 @@ uses
               specializest.includeoption(sto_has_generic);
 
             tempst.free;
+            tempst := nil;
 
             specialization_done(state);
 
@@ -2206,6 +2224,7 @@ uses
           end;
 
         generictypelist.free;
+        generictypelist := nil;
         if assigned(genericdef) then
           begin
             { check the hints of the found generic symbol }
@@ -2228,7 +2247,7 @@ uses
           genericdef:=tstoreddef(generate_specialization_phase2(context,genericdef,parse_class_parent,_prettyname));
         tt:=genericdef;
         if assigned(context) then
-          context.free;
+          context.free; // no nil needed
       end;
 
 
@@ -2446,6 +2465,7 @@ uses
               firstidx:=result.count;
 
               constraintdata.free;
+              constraintdata := nil;
             end
           else
             begin
@@ -2854,6 +2874,7 @@ uses
           pu:=tused_unit(pu.next);
         end;
       unitsyms.free;
+      unitsyms := nil;
       if assigned(hmodule.globalsymtable) then
         symtablestack.push(hmodule.globalsymtable);
       symtable:=genericdef.owner;
@@ -3043,7 +3064,9 @@ uses
           current_module.pendingspecializations.add(tstoreddef(readdlist[i]).typename,readdlist[i]);
 
         readdlist.free;
+        readdlist := nil;
         list.free;
+        list := nil;
       end;
 
 

+ 12 - 0
compiler/pinline.pas

@@ -166,8 +166,10 @@ implementation
             if not(assigned(sym)) then
               begin
                  p.free;
+                 p := nil;
                  if is_new then
                    p2.free;
+                   p2 := nil;
                  new_dispose_statement := cerrornode.create;
                  consume_all_until(_RKLAMMER);
                  consume(_RKLAMMER);
@@ -218,6 +220,7 @@ implementation
                  p.free;
                  p:=factor(false,[]);
                  p.free;
+                 p := nil;
                  consume(_RKLAMMER);
                  new_dispose_statement:=cnothingnode.create;
                  exit;
@@ -229,6 +232,7 @@ implementation
                  p.free;
                  p:=factor(false,[]);
                  p.free;
+                 p := nil;
                  consume(_RKLAMMER);
                  new_dispose_statement:=cerrornode.create;
                  exit;
@@ -238,6 +242,7 @@ implementation
               begin
                  Message(parser_e_pointer_to_class_expected);
                  p.free;
+                 p := nil;
                  new_dispose_statement:=factor(false,[]);
                  consume_all_until(_RKLAMMER);
                  consume(_RKLAMMER);
@@ -268,6 +273,7 @@ implementation
                  else
                   Message(parser_e_expr_have_to_be_destructor_call);
                  p.free;
+                 p := nil;
                  new_dispose_statement:=cerrornode.create;
               end
             else
@@ -345,6 +351,7 @@ implementation
                  if is_typeparam(p.resultdef) then
                    begin
                       p.free;
+                      p := nil;
                       consume(_RKLAMMER);
                       new_dispose_statement:=cnothingnode.create;
                       exit;
@@ -452,6 +459,7 @@ implementation
            consume_all_until(_RKLAMMER);
            consume(_RKLAMMER);
            p1.free;
+           p1 := nil;
            new_function:=cerrornode.create;
            exit;
          end;
@@ -462,6 +470,7 @@ implementation
            consume_all_until(_RKLAMMER);
            consume(_RKLAMMER);
            p1.free;
+           p1 := nil;
            new_function:=cerrornode.create;
            exit;
          end;
@@ -486,6 +495,7 @@ implementation
                consume_all_until(_RKLAMMER);
                consume(_RKLAMMER);
                p1.free;
+               p1 := nil;
                new_function:=cerrornode.create;
                exit;
              end;
@@ -512,6 +522,7 @@ implementation
               the pointer to the object }
             p1.resultdef:=p2.resultdef;
             p2.free;
+            p2 := nil;
             consume(_RKLAMMER);
           end;
         new_function:=p1;
@@ -643,6 +654,7 @@ implementation
          end;
         ppn.left:=nil;
         paras.free;
+        paras := nil;
         result.free;
         result:=newblock;
       end;

+ 11 - 0
compiler/pkgutil.pas

@@ -286,6 +286,7 @@ implementation
       if not inppu.openfile then
        begin
          inppu.free;
+         inppu := nil;
          Comment(V_Error,'Could not open : '+PPUFn);
          Exit;
        end;
@@ -293,6 +294,7 @@ implementation
       if not inppu.CheckPPUId then
        begin
          inppu.free;
+         inppu := nil;
          Comment(V_Error,'Not a PPU File : '+PPUFn);
          Exit;
        end;
@@ -300,6 +302,7 @@ implementation
       if ppuversion<>CurrentPPUVersion then
        begin
          inppu.free;
+         inppu := nil;
          Comment(V_Error,'Wrong PPU Version '+tostr(ppuversion)+' in '+PPUFn);
          Exit;
        end;
@@ -307,6 +310,7 @@ implementation
       if (inppu.header.common.flags and uf_in_library)<>0 then
        begin
          inppu.free;
+         inppu := nil;
          Comment(V_Error,'PPU is already in a library : '+PPUFn);
          Exit;
        end;
@@ -314,6 +318,7 @@ implementation
       if (inppu.header.common.flags and (uf_static_linked or uf_no_link))=0 then
        begin
          inppu.free;
+         inppu := nil;
          Comment(V_Error,'PPU is not static linked : '+PPUFn);
          Exit;
        end;
@@ -340,7 +345,9 @@ implementation
         if b in [ibendinterface,ibend] then
          begin
            inppu.free;
+           inppu := nil;
            outppu.free;
+           outppu := nil;
            Comment(V_Error,'No files to be linked found : '+PPUFn);
            Exit;
          end;
@@ -438,7 +445,9 @@ implementation
       outppu.flush;
       outppu.writeheader;
       outppu.free;
+      outppu := nil;
       inppu.free;
+      inppu := nil;
       Result:=True;
     end;
 
@@ -866,9 +875,11 @@ implementation
         end;
 
       alreadyloaded.free;
+      alreadyloaded := nil;
       for i:=0 to cache.count-1 do
         dispose(pcacheentry(cache[i]));
       cache.free;
+      cache := nil;
     end;
 
 

+ 10 - 0
compiler/pmodules.pas

@@ -82,6 +82,7 @@ implementation
                KeepShared.Concat(s);
             end;
            DLLscanner.Free;
+           DLLscanner := nil;
            { Recreate import section }
            if (target_info.system in [system_i386_win32,system_i386_wdosx]) then
             begin
@@ -98,6 +99,7 @@ implementation
               curr.linkOtherSharedLibs.add(s,link_always);
             end;
            KeepShared.Free;
+           KeepShared := nil;
          end;
 
         { allow a target-specific pass over all assembler code (used by LLVM
@@ -311,6 +313,7 @@ implementation
               internalerror(2024020701);
             curr.used_units.Remove(uu);
             uu.Free;
+            uu := nil;
            { remove the module }
             loaded_units.Remove(hp);
             unloaded_units.Concat(hp);
@@ -711,6 +714,7 @@ implementation
                 current_scanner.tempopeninputfile;
               end;
            state.free;
+           state := nil;
          end;
 
       begin
@@ -2164,6 +2168,7 @@ type
              Message1(unit_f_errors_in_unit,tostr(Errorcount));
              status.skip_error:=true;
              pkg.free;
+             pkg := nil;
              exit;
            end;
 
@@ -2245,6 +2250,7 @@ type
             Message1(unit_f_errors_in_unit,tostr(Errorcount));
             status.skip_error:=true;
             pkg.free;
+            pkg := nil;
             exit;
           end;
 
@@ -2304,6 +2310,7 @@ type
                       begin
                         loaded_units.remove(hp);
                         hp.free;
+                        hp := nil;
                       end;
                     hp:=hp2;
                   end;
@@ -2321,6 +2328,7 @@ type
               end;
 
              pkg.free;
+             pkg := nil;
           end;
       end;
 
@@ -2362,6 +2370,7 @@ type
                  begin
                    loaded_units.remove(hp);
                    hp.free;
+                   hp := nil;
                  end;
                hp:=hp2;
              end;
@@ -2616,6 +2625,7 @@ type
                call_through_new_name(main_procinfo.procdef,target_info.cprefix+'FPC_LIBMAIN');
                initpd:=main_procinfo.procdef;
                main_procinfo.free;
+               main_procinfo := nil;
              end;
 
            main_procinfo:=create_main_proc(make_mangledname('',curr.localsymtable,mainaliasname),potype_proginit,curr.localsymtable);

+ 5 - 2
compiler/procdefutil.pas

@@ -700,6 +700,7 @@ implementation
             end;
         end;
       symstodo.free;
+      symstodo := nil;
     end;
 
 
@@ -1728,10 +1729,12 @@ implementation
             end;
 
           tocapture.free;
+          tocapture := nil;
         end;
 
       { not required anymore }
       capturedsyms.free;
+      capturedsyms := nil;
 
       if convertarg.mappings.count>0 then
         foreachnodestatic(pm_postprocess,tree,@convert_captured_sym,@convertarg);
@@ -1739,11 +1742,11 @@ implementation
       for i:=0 to convertarg.mappings.count-1 do
         begin
           mapping:=pconvert_mapping(convertarg.mappings[i]);
-          mapping^.selfnode.free;
+          mapping^.selfnode.free; // no nil needed
           dispose(mapping);
         end;
 
-      convertarg.mappings.free;
+      convertarg.mappings.free; // no nil needed
     end;
 
 

+ 6 - 0
compiler/procinfo.pas

@@ -264,10 +264,15 @@ implementation
     destructor tprocinfo.destroy;
       begin
          nestedprocs.free;
+         nestedprocs := nil;
          aktproccode.free;
+         aktproccode := nil;
          aktlocaldata.free;
+         aktlocaldata := nil;
          localrefsyms.free;
+         localrefsyms := nil;
          localrefdefs.free;
+         localrefdefs := nil;
       end;
 
     procedure tprocinfo.destroy_tree;
@@ -278,6 +283,7 @@ implementation
         while Assigned(hp.parent) do
           hp:=hp.parent;
         hp.Free;
+        hp := nil;
       end;
 
     procedure tprocinfo.addnestedproc(child: tprocinfo);

+ 7 - 0
compiler/psabiehpi.pas

@@ -183,6 +183,7 @@ implementation
         if not(actionlist.Empty) then
           Internalerror(2019020501);
         actionlist.Free;
+        actionlist := nil;
         inherited Destroy;
       end;
 
@@ -226,11 +227,17 @@ implementation
     destructor tpsabiehprocinfo.destroy;
       begin
          gcc_except_table_data.free;
+         gcc_except_table_data := nil;
          actionstack.free;
+         actionstack := nil;
          landingpadstack.free;
+         landingpadstack := nil;
          typefilterlist.free;
+         typefilterlist := nil;
          callsite_table_data.Free;
+         callsite_table_data := nil;
          action_table_data.Free;
+         action_table_data := nil;
          inherited;
       end;
 

+ 13 - 1
compiler/pstatmnt.pas

@@ -259,8 +259,11 @@ implementation
                    end;
                end;
              p.free;
+             p := nil;
              sl1.free;
+             sl1 := nil;
              sl2.free;
+             sl2 := nil;
 
              if token=_COMMA then
                consume(_COMMA)
@@ -548,6 +551,7 @@ implementation
               result:=create_for_in_loop(hloopvar,hloopbody,expr);
 
               expr.free;
+              expr := nil;
             end;
 
 
@@ -791,6 +795,7 @@ implementation
             for i:=withsymtablelist.count-1 downto 0 do
               symtablestack.pop(TSymtable(withsymtablelist[i]));
             withsymtablelist.free;
+            withsymtablelist := nil;
 
             { Finalize complex withnode with destroy of temp }
             if assigned(newblock) then
@@ -807,6 +812,7 @@ implementation
          else
           begin
             p.free;
+            p := nil;
             Message1(parser_e_false_with_expr,p.resultdef.GetTypeName);
             { try to recover from error }
             if try_to_consume(_COMMA) then
@@ -1031,7 +1037,10 @@ implementation
                        begin
                          symtablestack.pop(excepTSymtable);
                          if last.nodetype <> onn then
-                           excepTSymtable.free;
+                           begin
+                             excepTSymtable.free;
+                             excepTSymtable := nil;
+                           end;
                        end;
                      if not try_to_consume(_SEMICOLON) then
                         break;
@@ -1087,6 +1096,7 @@ implementation
              asmstat:=casmnode.create(hl);
              asmstat.fileinfo:=entrypos;
              asmreader.free;
+             asmreader := nil;
            end
          else
            Message(parser_f_assembler_reader_not_supported);
@@ -1310,6 +1320,7 @@ implementation
             consume(_RKLAMMER); {error}
         until nesting<0;
         tokenbuf.free;
+        tokenbuf := nil;
         { mark boundaries of assembler block, this is necessary for optimizer }
         hl.insert(tai_marker.create(mark_asmblockstart));
         hl.concat(tai_marker.create(mark_asmblockend));
@@ -1473,6 +1484,7 @@ implementation
                 else
                   searchsym(s,srsym,srsymtable);
                 p.free;
+                p := nil;
 
                 if assigned(srsym) and
                    (srsym.typ=labelsym) then

+ 5 - 0
compiler/psub.pas

@@ -688,6 +688,7 @@ implementation
        begin
          TFPList.FreeAndNilDisposing(tempinfo_flags_map,TypeInfo(ttempinfo_flags_entry));
          code.free;
+         code := nil;
          inherited destroy;
        end;
 
@@ -1412,6 +1413,7 @@ implementation
         nodeset:=THashSet.Create(32,false,false);
         foreachnode(code,@store_node_tempflags,nodeset);
         nodeset.free;
+        nodeset := nil;
       end;
 
 
@@ -1869,6 +1871,7 @@ implementation
                 begin
                   aktproccode.remove(ai);
                   ai.free;
+                  ai := nil;
                   anode.currenttai:=nil;
                 end;
             end;
@@ -2343,12 +2346,14 @@ implementation
           end;
 
         dfabuilder.free;
+        dfabuilder := nil;
 
         { restore symtablestack }
         remove_from_symtablestack;
 
         { restore }
         templist.free;
+        templist := nil;
         current_settings.maxfpuregisters:=oldmaxfpuregisters;
         current_filepos:=oldfilepos;
         current_structdef:=old_current_structdef;

+ 1 - 0
compiler/ptconst.pas

@@ -146,6 +146,7 @@ implementation
           end;
 
         tcbuilder.free;
+        tcbuilder := nil;
         current_filepos:=storefilepos;
       end;
 

+ 6 - 0
compiler/ptype.pas

@@ -149,6 +149,7 @@ implementation
                      searchsym(upper(hs),srsym,srsymtable);
                      { we don't need the forwarddef anymore, dispose it }
                      hpd.free;
+                     hpd := nil;
                      tabstractpointerdef(def).pointeddef:=nil; { if error occurs }
                      { was a type sym found ? }
                      if assigned(srsym) and
@@ -341,6 +342,7 @@ implementation
                    end;
                  parse_nested_types(def,isfowarddef,true,structdefstack);
                  structdefstack.free;
+                 structdefstack := nil;
                  result:=true;
                  exit;
                end;
@@ -1270,6 +1272,7 @@ implementation
                else
                  Message(sym_e_error_in_type_def);
                pt2.free;
+               pt2 := nil;
              end
            else
              begin
@@ -1393,6 +1396,7 @@ implementation
                  Message(sym_e_error_in_type_def);
              end;
            pt1.free;
+           pt1 := nil;
            block_type:=old_block_type;
         end;
 
@@ -1644,6 +1648,7 @@ implementation
                            Message(sym_e_error_in_type_def)
                        end;
                      pt.free;
+                     pt := nil;
                    end;
 
                   { if we are not at the first dimension, add the new arrray
@@ -1910,6 +1915,7 @@ implementation
                        else
                         Message(parser_e_illegal_expression);
                        p.free;
+                       p := nil;
                        { please leave that a note, allows type save }
                        { declarations in the win32 units ! }
                        if (not first) and (v<=l) and (not enumdupmsg) then

+ 2 - 0
compiler/rasm.pas

@@ -97,7 +97,9 @@ unit rasm;
     destructor tasmreader.destroy;
       begin
         locallabels.Free;
+        locallabels := nil;
         iasmops.Free;
+        iasmops := nil;
         inherited destroy;
       end;
 

+ 2 - 1
compiler/rautils.pas

@@ -520,6 +520,7 @@ Begin
   expr:=TExprParse.create;
   CalculateExpression:=expr.Evaluate(expression);
   expr.Free;
+  expr := nil;
 end;
 
 
@@ -1271,7 +1272,7 @@ var
   i : longint;
 Begin
   for i:=1 to max_operands do
-   Operands[i].free;
+   FreeAndNil(Operands[i]);
 end;
 
 

+ 7 - 1
compiler/rgobj.pas

@@ -498,11 +498,15 @@ unit rgobj;
         live_registers.done;
 
         move_garbage.free;
+        move_garbage := nil;
         worklist_moves.free;
+        worklist_moves := nil;
 
         dispose_reginfo;
         extended_backwards.free;
+        extended_backwards := nil;
         backwards_was_first.free;
+        backwards_was_first := nil;
       end;
 
 
@@ -683,6 +687,7 @@ unit rgobj;
             end;
         until endspill;
         ibitmap.free;
+        ibitmap := nil;
 
         translate_registers(list);
 
@@ -695,7 +700,7 @@ unit rgobj;
         }
 
         for i:=0 to High(spillinfo) do
-          spillinfo[i].interferences.Free;
+          FreeAndNil(spillinfo[i].interferences);
         spillinfo:=nil;
       end;
 
@@ -2552,6 +2557,7 @@ unit rgobj;
             end;
         list.insertlistafter(headertai,templist);
         templist.free;
+        templist := nil;
         { Walk through all instructions, we can start with the headertai,
           because before the header tai is only symbols }
         p:=headertai;

+ 24 - 2
compiler/scanner.pas

@@ -1098,11 +1098,17 @@ type
   class destructor texprvalue.destroydefs;
     begin
       setdef.free;
+      setdef := nil;
       sintdef.free;
+      sintdef := nil;
       uintdef.free;
+      uintdef := nil;
       booldef.free;
+      booldef := nil;
       strdef.free;
+      strdef := nil;
       realdef.free;
+      realdef := nil;
     end;
 
   constructor texprvalue.create_const(c: tconstsym);
@@ -2264,6 +2270,7 @@ type
                     else
                       result:=texprvalue.create_int(0);
                     exprvalue.free;
+                    exprvalue := nil;
                     if current_scanner.preproc_token =_RKLAMMER then
                       preproc_consume(_RKLAMMER)
                     else
@@ -2279,6 +2286,7 @@ type
                     else
                       result:=texprvalue.create_bool(false); {Just to have something}
                     exprvalue.free;
+                    exprvalue := nil;
                   end
                 else
                 if (current_scanner.preproc_pattern='TRUE') then
@@ -2455,6 +2463,7 @@ type
                else
                  Message(scan_e_error_in_preproc_expr);
                exprvalue.free;
+               exprvalue := nil;
              end
            else
              Message(scan_e_error_in_preproc_expr);
@@ -2508,7 +2517,9 @@ type
                      result:=texprvalue.create_bool(false); {Just to have something}
                  end;
                hs1.free;
+               hs1 := nil;
                hs2.free;
+               hs2 := nil;
              end
            else
              break;
@@ -2538,6 +2549,7 @@ type
           end;
         valuedescr:=hs.asStr;
         hs.free;
+        hs := nil;
       end;
 
     procedure dir_if;
@@ -2720,6 +2732,7 @@ type
              else
                Message(scan_e_preproc_syntax_error);
              exprvalue.free;
+             exprvalue := nil;
           end
         else
           Message(scan_e_preproc_syntax_error);
@@ -3094,8 +3107,12 @@ type
         if not inputfile.closed then
           closeinputfile;
         if inputfile.is_macro then
-          inputfile.free;
+          begin
+            inputfile.free;
+            inputfile := nil;
+          end;
         ignoredirectives.free;
+        ignoredirectives := nil;
       end;
 
 
@@ -3227,7 +3244,7 @@ type
            inputfile.close;
            inputfile:=inputfile.next;
            if assigned(to_dispose) then
-             to_dispose.free;
+             to_dispose.free; // no nil needed
            restoreinputfile;
          end;
       end;
@@ -3923,6 +3940,7 @@ type
                         if assigned(pmsg) then
                           dispose(pmsg);
                         msgset.free;
+                        msgset := nil;
                       end;
                     ST_LINE:
                       begin
@@ -6872,6 +6890,7 @@ exit_label:
             result:=false;
           end;
         hs.free;
+        hs := nil;
       end;
 
 
@@ -6891,6 +6910,7 @@ exit_label:
             result:=false;
           end;
         hs.free;
+        hs := nil;
       end;
 
 
@@ -6998,7 +7018,9 @@ exit_label:
     procedure DoneScanner;
       begin
         turbo_scannerdirectives.Free;
+        turbo_scannerdirectives := nil;
         mac_scannerdirectives.Free;
+        mac_scannerdirectives := nil;
         DoneWideString(patternw);
       end;
 

+ 1 - 0
compiler/switches.pas

@@ -463,6 +463,7 @@ procedure flushpendingswitchesstate;
         pendingstate.nextmessagerecord:=nil;
       end;
     msgset.free;
+    msgset := nil;
     { process pending calling convention changes (calling x) }
     if pendingstate.nextcallingstr<>'' then
       begin

+ 3 - 0
compiler/symbase.pas

@@ -270,9 +270,11 @@ implementation
           exit;
         Clear;
         DefList.Free;
+        DefList := nil;
         { SymList can already be disposed or set to nil for withsymtable, }
         { but in that case Free does nothing                              }
         SymList.Free;
+        SymList := nil;
         stringdispose(name);
         stringdispose(realname);
       end;
@@ -522,5 +524,6 @@ initialization
 
 finalization
   memrealnames.free;
+  memrealnames := nil;
 {$endif MEMDEBUG}
 end.

+ 2 - 1
compiler/symcreat.pas

@@ -180,7 +180,7 @@ implementation
     begin
       if sstate.valid then
         begin
-          sstate.new_scanner.free;
+          sstate.new_scanner.free; // no nil needed
           set_current_scanner(sstate.old_scanner);
           current_filepos:=sstate.old_filepos;
           token:=sstate.old_token;
@@ -724,6 +724,7 @@ implementation
             str:=str+'__fpc_ord2enum.put(JLInteger.valueOf('+tostr(enumsym.value)+'),'+enumname+');';
         end;
       orderedenums.free;
+      orderedenums := nil;
       str:=str+' end;';
       str_parse_method_impl(str,pd,true);
     end;

+ 11 - 1
compiler/symdef.pas

@@ -1598,6 +1598,7 @@ implementation
           targetinfos[target_info.system]^.alignment.recordalignmin);
         result.add_fields_from_deflist(fieldlist);
         fieldlist.free;
+        fieldlist := nil;
       end;
 
 
@@ -1648,6 +1649,7 @@ implementation
           arrdef:=nil;
         recdef.add_fields_from_deflist(fields);
         fields.free;
+        fields := nil;
       end;
 
     function make_mangledname(const typeprefix:TSymStr;st:TSymtable;const suffix:TSymStr):TSymStr;
@@ -1981,6 +1983,7 @@ implementation
       begin
         TFPList.FreeAndNilDisposing(interfacesderef,typeinfo(tderef));
         interfaces.free;
+        interfaces := nil;
         inherited destroy;
       end;
 
@@ -2113,9 +2116,12 @@ implementation
             generictokenbuf:=nil;
           end;
         rtti_attribute_list.free;
+        rtti_attribute_list := nil;
         genericparas.free;
+        genericparas := nil;
         TFPList.FreeAndNilDisposing(genericparaderefs,typeinfo(tderef));
         genconstraintdata.free;
+        genconstraintdata := nil;
 {$ifndef symansistr}
         stringdispose(_fullownerhierarchyname);
 {$endif not symansistr}
@@ -3295,8 +3301,10 @@ implementation
         n : tnode;
       begin
         constructorcall.free;
+        constructorcall := nil;
         for n in paras do
           n.free;
+          n := nil;
         inherited destroy;
       end;
 
@@ -3390,6 +3398,7 @@ implementation
     destructor trtti_attribute_list.destroy;
       begin
         rtti_attributes.Free;
+        rtti_attributes := nil;
         inherited destroy;
       end;
 
@@ -4831,6 +4840,7 @@ implementation
         stringdispose(objrealname);
         stringdispose(import_lib);
         tcinitcode.free;
+        tcinitcode := nil;
         inherited destroy;
       end;
 
@@ -6783,7 +6793,7 @@ implementation
 {$ifdef MEMDEBUG}
             memprocnodetree.start;
 {$endif MEMDEBUG}
-            tnode(inlininginfo^.code).free;
+            FreeAndNil(tnode(inlininginfo^.code));
 {$ifdef MEMDEBUG}
             memprocnodetree.start;
 {$endif MEMDEBUG}

+ 11 - 4
compiler/symsym.pas

@@ -26,7 +26,7 @@ interface
 
     uses
        { common }
-       cutils,compinnr,
+       sysutils,cutils,compinnr,
        { target }
        globtype,globals,widestr,constexp,
        { symtable }
@@ -736,6 +736,7 @@ implementation
     destructor tstoredsym.destroy;
       begin
         rtti_attribute_list.free;
+        rtti_attribute_list := nil;
         inherited destroy;
       end;
 
@@ -986,10 +987,13 @@ implementation
     destructor tprocsym.destroy;
       begin
         FProcdefList.Free;
-        if assigned(FProcdefDerefList) then
-          FProcdefDerefList.Free;
+        FProcdefList := nil;
+        FProcdefDerefList.Free;
+        FProcdefDerefList := nil;
         fgenprocsymovlds.free;
+        fgenprocsymovlds := nil;
         fgenprocsymovldsderefs.free;
+        fgenprocsymovldsderefs := nil;
         inherited destroy;
       end;
 
@@ -1637,8 +1641,9 @@ implementation
         pap : tpropaccesslisttypes;
       begin
          for pap:=low(tpropaccesslisttypes) to high(tpropaccesslisttypes) do
-           propaccesslist[pap].free;
+           FreeAndNil(propaccesslist[pap]);
          parast.free;
+         parast := nil;
          inherited destroy;
       end;
 
@@ -2556,6 +2561,7 @@ implementation
       begin
         if assigned(ref) then
           ref.free;
+          ref := nil;
         inherited destroy;
       end;
 
@@ -3213,6 +3219,7 @@ implementation
     procedure done_symsym;
       begin
         syssym_list.free;
+        syssym_list := nil;
       end;
 
 

+ 11 - 0
compiler/symtable.pas

@@ -1220,6 +1220,7 @@ implementation
           exit;
 {$ifdef llvm}
         fllvmst.free;
+        fllvmst := nil;
 {$endif llvm}
         for mop:=low(tmanagementoperator) to high(tmanagementoperator) do
           TFPList.FreeAndNilDisposing(mop_list[mop],TypeInfo(tmanagementoperator_offset_entry));
@@ -1769,6 +1770,7 @@ implementation
           end;
         { we don't need to remove the entries as they become part of list }
         sublist.free;
+        sublist := nil;
       end;
 
     procedure tabstractrecordsymtable.get_managementoperator_offset_list(mop:tmanagementoperator;list:tfplist);
@@ -2106,6 +2108,7 @@ implementation
     destructor tllvmshadowsymtable.destroy;
       begin
         symdeflist.free;
+        symdeflist := nil;
       end;
 
 
@@ -2406,7 +2409,9 @@ implementation
         buildmapping(tempsymlist, variantstarts);
 
         variantstarts.free;
+        variantstarts := nil;
         tempsymlist.free;
+        tempsymlist := nil;
       end;
 
 {$endif llvm}
@@ -2826,6 +2831,7 @@ implementation
         if refcount>1 then
           exit;
         withrefnode.free;
+        withrefnode := nil;
         { Disable SymList because we don't Own it }
         SymList:=nil;
         inherited destroy;
@@ -5063,12 +5069,17 @@ implementation
       begin
         generrorsym.owner:=nil;
         generrorsym.free;
+        generrorsym := nil;
         generrordef.owner:=nil;
         generrordef.free;
+        generrordef := nil;
         initialmacrosymtable.free;
+        initialmacrosymtable := nil;
         macrosymtablestack.free;
+        macrosymtablestack := nil;
 {$ifdef UNITALIASES}
         unitaliases.free;
+        unitaliases := nil;
 {$endif}
      end;
 

+ 7 - 2
compiler/symtype.pas

@@ -626,8 +626,8 @@ implementation
     destructor  Tsym.destroy;
       begin
         stringdispose(deprecatedmsg);
-        if assigned(RefList) then
-          RefList.Free;
+        RefList.Free;
+        RefList := nil;
         inherited Destroy;
       end;
 
@@ -1344,10 +1344,15 @@ initialization
 
 finalization
   memmanglednames.free;
+  memmanglednames := nil;
   memprocpara.free;
+  memprocpara := nil;
   memprocparast.free;
+  memprocparast := nil;
   memproclocalst.free;
+  memproclocalst := nil;
   memprocnodetree.free;
+  memprocnodetree := nil;
 {$endif MEMDEBUG}
 
 end.

+ 1 - 0
compiler/verbose.pas

@@ -190,6 +190,7 @@ implementation
             pstate:=pstate^.next;
           end;
         msgset.free;
+        msgset := nil;
       end;
 
     procedure FreeLocalVerbosity(var fstate : pmessagestaterecord);

+ 5 - 3
compiler/wpobase.pas

@@ -384,7 +384,7 @@ implementation
       if assigned(fcalledvmtentries) then
         begin
           for i:=0 to fcalledvmtentries.count-1 do
-            tcalledvmtentries(fcalledvmtentries[i]).free;
+            tcalledvmtentries(fcalledvmtentries[i]).free; // no nil needed
           fcalledvmtentries.free;
           fcalledvmtentries:=nil;
         end;
@@ -529,7 +529,7 @@ implementation
                   if assigned(fdest.wpoinfouse[wpotype]) then
                     begin
                       cgmessage2(wpo_duplicate_wpotype,wpo2str[wpotype],sectionname);
-                      fdest.wpoinfouse[wpotype].free;
+                      FreeAndNil(fdest.wpoinfouse[wpotype]);
                     end;
                   { process the section }
                   fdest.wpoinfouse[wpotype]:=sectionhandler.create;
@@ -597,6 +597,7 @@ implementation
   destructor twpofilewriter.destroy;
     begin
       fsectioncontents.free;
+      fsectioncontents := nil;
       inherited destroy;
     end;
 
@@ -800,7 +801,7 @@ implementation
       fwpocomponents:=nil;
       for i:=low(wpoinfouse) to high(wpoinfouse) do
         if assigned(wpoinfouse[i]) then
-          wpoinfouse[i].free;
+          FreeAndNil(wpoinfouse[i]);
       inherited destroy;
     end;
 
@@ -829,6 +830,7 @@ implementation
   destructor tcalledvmtentries.destroy;
     begin
       fcalledentries.free;
+      fcalledentries := nil;
       inherited destroy;
     end;