packages feed

ghc 9.14.1 → 9.14.2

raw patch · 231 files changed

+9989/−5774 lines, 231 filesdep ~ghc-bootdep ~ghc-boot-thdep ~ghc-boot-th-nextPVP: major bump suggested

API removals or changes: PVP suggests a major version bump

Dependency ranges changed: ghc-boot, ghc-boot-th, ghc-boot-th-next, ghc-heap, ghc-internal, ghci

API changes (from Hackage documentation)

- GHC: [modBreaks_locs] :: ModBreaks -> Array BreakTickIndex SrcSpan
- GHC.Builtin.Names: zonkAnyTyConKey :: Unique
- GHC.Builtin.Types: zonkAnyTyCon :: TyCon
- GHC.ByteCode.Types: [modBreaks_locs] :: ModBreaks -> Array BreakTickIndex SrcSpan
- GHC.CmmToAsm.Reg.Linear.Base: instance GHC.Internal.Classes.Eq GHC.CmmToAsm.Reg.Linear.Base.Loc
- GHC.CmmToAsm.Reg.Linear.Base: instance GHC.Internal.Classes.Eq GHC.CmmToAsm.Reg.Linear.Base.RealRegUsage
- GHC.CmmToAsm.Reg.Linear.Base: instance GHC.Internal.Classes.Ord GHC.CmmToAsm.Reg.Linear.Base.Loc
- GHC.CmmToAsm.Reg.Linear.Base: instance GHC.Internal.Classes.Ord GHC.CmmToAsm.Reg.Linear.Base.RealRegUsage
- GHC.CmmToAsm.Reg.Linear.Base: instance GHC.Internal.Show.Show GHC.CmmToAsm.Reg.Linear.Base.Loc
- GHC.CmmToAsm.Reg.Target: mapRegFormatSet :: HasDebugCallStack => (Reg -> Reg) -> UniqSet RegWithFormat -> UniqSet RegWithFormat
- GHC.CmmToLlvm.Config: [llvmCgAvxEnabled] :: LlvmCgConfig -> Bool
- GHC.Core.Opt.OccurAnal: DoBinderSwap :: OutVar -> MCoercion -> BinderSwapDecision
- GHC.Core.Opt.OccurAnal: NoBinderSwap :: BinderSwapDecision
- GHC.Core.Opt.OccurAnal: data BinderSwapDecision
- GHC.Core.Opt.OccurAnal: scrutOkForBinderSwap :: OutExpr -> BinderSwapDecision
- GHC.Core.Opt.Simplify.Utils: updModeForRules :: SimplMode -> SimplMode
- GHC.Driver.MakeSem: SemaphoreName :: String -> SemaphoreName
- GHC.Driver.MakeSem: [getSemaphoreName] :: SemaphoreName -> String
- GHC.Driver.MakeSem: data Semaphore
- GHC.Driver.MakeSem: newtype SemaphoreName
- GHC.HsToCore.Breakpoints: [modBreaks_locs] :: ModBreaks -> Array BreakTickIndex SrcSpan
- GHC.HsToCore.Pmc: addHsScrutTmCs :: [LHsExpr GhcTc] -> [Id] -> DsM a -> DsM a
- GHC.Stg.EnforceEpt.TagSig: TagProper :: TagInfo
- GHC.Stg.EnforceEpt.TagSig: TagSig :: TagInfo -> TagSig
- GHC.Stg.EnforceEpt.TagSig: TagTagged :: TagInfo
- GHC.Stg.EnforceEpt.TagSig: newtype TagSig
- GHC.Stg.EnforceEpt.Types: isTaggedInfo :: TagInfo -> Bool
- GHC.Stg.EnforceEpt.Types: lookupSig :: forall (p :: StgPass). TagEnv p -> Id -> Maybe TagSig
- GHC.StgToCmm.Config: [stgToCmmTickyAP] :: StgToCmmConfig -> Bool
- GHC.StgToCmm.Monad: [stgToCmmTickyAP] :: StgToCmmConfig -> Bool
- GHC.StgToJS.Regs: R1 :: StgReg
- GHC.StgToJS.Regs: R10 :: StgReg
- GHC.StgToJS.Regs: R100 :: StgReg
- GHC.StgToJS.Regs: R101 :: StgReg
- GHC.StgToJS.Regs: R102 :: StgReg
- GHC.StgToJS.Regs: R103 :: StgReg
- GHC.StgToJS.Regs: R104 :: StgReg
- GHC.StgToJS.Regs: R105 :: StgReg
- GHC.StgToJS.Regs: R106 :: StgReg
- GHC.StgToJS.Regs: R107 :: StgReg
- GHC.StgToJS.Regs: R108 :: StgReg
- GHC.StgToJS.Regs: R109 :: StgReg
- GHC.StgToJS.Regs: R11 :: StgReg
- GHC.StgToJS.Regs: R110 :: StgReg
- GHC.StgToJS.Regs: R111 :: StgReg
- GHC.StgToJS.Regs: R112 :: StgReg
- GHC.StgToJS.Regs: R113 :: StgReg
- GHC.StgToJS.Regs: R114 :: StgReg
- GHC.StgToJS.Regs: R115 :: StgReg
- GHC.StgToJS.Regs: R116 :: StgReg
- GHC.StgToJS.Regs: R117 :: StgReg
- GHC.StgToJS.Regs: R118 :: StgReg
- GHC.StgToJS.Regs: R119 :: StgReg
- GHC.StgToJS.Regs: R12 :: StgReg
- GHC.StgToJS.Regs: R120 :: StgReg
- GHC.StgToJS.Regs: R121 :: StgReg
- GHC.StgToJS.Regs: R122 :: StgReg
- GHC.StgToJS.Regs: R123 :: StgReg
- GHC.StgToJS.Regs: R124 :: StgReg
- GHC.StgToJS.Regs: R125 :: StgReg
- GHC.StgToJS.Regs: R126 :: StgReg
- GHC.StgToJS.Regs: R127 :: StgReg
- GHC.StgToJS.Regs: R128 :: StgReg
- GHC.StgToJS.Regs: R13 :: StgReg
- GHC.StgToJS.Regs: R14 :: StgReg
- GHC.StgToJS.Regs: R15 :: StgReg
- GHC.StgToJS.Regs: R16 :: StgReg
- GHC.StgToJS.Regs: R17 :: StgReg
- GHC.StgToJS.Regs: R18 :: StgReg
- GHC.StgToJS.Regs: R19 :: StgReg
- GHC.StgToJS.Regs: R2 :: StgReg
- GHC.StgToJS.Regs: R20 :: StgReg
- GHC.StgToJS.Regs: R21 :: StgReg
- GHC.StgToJS.Regs: R22 :: StgReg
- GHC.StgToJS.Regs: R23 :: StgReg
- GHC.StgToJS.Regs: R24 :: StgReg
- GHC.StgToJS.Regs: R25 :: StgReg
- GHC.StgToJS.Regs: R26 :: StgReg
- GHC.StgToJS.Regs: R27 :: StgReg
- GHC.StgToJS.Regs: R28 :: StgReg
- GHC.StgToJS.Regs: R29 :: StgReg
- GHC.StgToJS.Regs: R3 :: StgReg
- GHC.StgToJS.Regs: R30 :: StgReg
- GHC.StgToJS.Regs: R31 :: StgReg
- GHC.StgToJS.Regs: R32 :: StgReg
- GHC.StgToJS.Regs: R33 :: StgReg
- GHC.StgToJS.Regs: R34 :: StgReg
- GHC.StgToJS.Regs: R35 :: StgReg
- GHC.StgToJS.Regs: R36 :: StgReg
- GHC.StgToJS.Regs: R37 :: StgReg
- GHC.StgToJS.Regs: R38 :: StgReg
- GHC.StgToJS.Regs: R39 :: StgReg
- GHC.StgToJS.Regs: R4 :: StgReg
- GHC.StgToJS.Regs: R40 :: StgReg
- GHC.StgToJS.Regs: R41 :: StgReg
- GHC.StgToJS.Regs: R42 :: StgReg
- GHC.StgToJS.Regs: R43 :: StgReg
- GHC.StgToJS.Regs: R44 :: StgReg
- GHC.StgToJS.Regs: R45 :: StgReg
- GHC.StgToJS.Regs: R46 :: StgReg
- GHC.StgToJS.Regs: R47 :: StgReg
- GHC.StgToJS.Regs: R48 :: StgReg
- GHC.StgToJS.Regs: R49 :: StgReg
- GHC.StgToJS.Regs: R5 :: StgReg
- GHC.StgToJS.Regs: R50 :: StgReg
- GHC.StgToJS.Regs: R51 :: StgReg
- GHC.StgToJS.Regs: R52 :: StgReg
- GHC.StgToJS.Regs: R53 :: StgReg
- GHC.StgToJS.Regs: R54 :: StgReg
- GHC.StgToJS.Regs: R55 :: StgReg
- GHC.StgToJS.Regs: R56 :: StgReg
- GHC.StgToJS.Regs: R57 :: StgReg
- GHC.StgToJS.Regs: R58 :: StgReg
- GHC.StgToJS.Regs: R59 :: StgReg
- GHC.StgToJS.Regs: R6 :: StgReg
- GHC.StgToJS.Regs: R60 :: StgReg
- GHC.StgToJS.Regs: R61 :: StgReg
- GHC.StgToJS.Regs: R62 :: StgReg
- GHC.StgToJS.Regs: R63 :: StgReg
- GHC.StgToJS.Regs: R64 :: StgReg
- GHC.StgToJS.Regs: R65 :: StgReg
- GHC.StgToJS.Regs: R66 :: StgReg
- GHC.StgToJS.Regs: R67 :: StgReg
- GHC.StgToJS.Regs: R68 :: StgReg
- GHC.StgToJS.Regs: R69 :: StgReg
- GHC.StgToJS.Regs: R7 :: StgReg
- GHC.StgToJS.Regs: R70 :: StgReg
- GHC.StgToJS.Regs: R71 :: StgReg
- GHC.StgToJS.Regs: R72 :: StgReg
- GHC.StgToJS.Regs: R73 :: StgReg
- GHC.StgToJS.Regs: R74 :: StgReg
- GHC.StgToJS.Regs: R75 :: StgReg
- GHC.StgToJS.Regs: R76 :: StgReg
- GHC.StgToJS.Regs: R77 :: StgReg
- GHC.StgToJS.Regs: R78 :: StgReg
- GHC.StgToJS.Regs: R79 :: StgReg
- GHC.StgToJS.Regs: R8 :: StgReg
- GHC.StgToJS.Regs: R80 :: StgReg
- GHC.StgToJS.Regs: R81 :: StgReg
- GHC.StgToJS.Regs: R82 :: StgReg
- GHC.StgToJS.Regs: R83 :: StgReg
- GHC.StgToJS.Regs: R84 :: StgReg
- GHC.StgToJS.Regs: R85 :: StgReg
- GHC.StgToJS.Regs: R86 :: StgReg
- GHC.StgToJS.Regs: R87 :: StgReg
- GHC.StgToJS.Regs: R88 :: StgReg
- GHC.StgToJS.Regs: R89 :: StgReg
- GHC.StgToJS.Regs: R9 :: StgReg
- GHC.StgToJS.Regs: R90 :: StgReg
- GHC.StgToJS.Regs: R91 :: StgReg
- GHC.StgToJS.Regs: R92 :: StgReg
- GHC.StgToJS.Regs: R93 :: StgReg
- GHC.StgToJS.Regs: R94 :: StgReg
- GHC.StgToJS.Regs: R95 :: StgReg
- GHC.StgToJS.Regs: R96 :: StgReg
- GHC.StgToJS.Regs: R97 :: StgReg
- GHC.StgToJS.Regs: R98 :: StgReg
- GHC.StgToJS.Regs: R99 :: StgReg
- GHC.StgToJS.Regs: data StgReg
- GHC.StgToJS.Regs: instance GHC.Internal.Enum.Bounded GHC.StgToJS.Regs.StgReg
- GHC.StgToJS.Regs: instance GHC.Internal.Enum.Enum GHC.StgToJS.Regs.StgReg
- GHC.StgToJS.Regs: instance GHC.Internal.Show.Show GHC.StgToJS.Regs.StgReg
- GHC.StgToJS.Regs: intToJSReg :: Int -> StgReg
- GHC.StgToJS.Regs: jsRegToInt :: StgReg -> Int
- GHC.StgToJS.Rts.Types: withRegs :: StgReg -> StgReg -> (StgReg -> JStgStat) -> JStgStat
- GHC.Tc.Utils.Instantiate: instantiateSigma :: CtOrigin -> ConcreteTyVars -> [TyVar] -> TcThetaType -> TcSigmaType -> TcM ([TcTyVar], HsWrapper, TcSigmaType)
- GHC.Tc.Utils.Monad: newZonkAnyType :: Kind -> TcM Type
- GHC.Tc.Utils.TcMType: newConcreteTyVarX :: ConcreteTvOrigin -> Subst -> TyVar -> TcM (Subst, TcTyVar)
- GHC.Tc.Utils.TcMType: newMetaTyVarBndrsX :: Subst -> [VarBndr TyVar vis] -> TcM (Subst, [VarBndr TcTyVar vis])
- GHC.Tc.Utils.TcMType: newOpenBoxedTypeKind :: TcM TcKind
- GHC.Tc.Utils.TcMType: newOpenFlexiFRRTyVar :: FixedRuntimeRepContext -> TcM TcTyVar
- GHC.Tc.Utils.TcType: isZonkAnyTy :: Type -> Bool
- GHC.Types.Basic: isActive :: CompilerPhase -> Activation -> Bool
- GHC.Types.Basic: laterPhase :: CompilerPhase -> CompilerPhase -> CompilerPhase
- GHC.Types.Error: instance GHC.Types.Error.Diagnostic e => GHC.Utils.Json.ToJson (GHC.Types.Error.Messages e)
- GHC.Types.Error: instance GHC.Types.Error.Diagnostic e => GHC.Utils.Json.ToJson (GHC.Types.Error.MsgEnvelope e)
- GHC.Unit.Env: [homeUnitEnv_unit_dbs] :: HomeUnitEnv -> Maybe [UnitDatabase UnitId]
- GHC.Unit.Env: ue_unit_dbs :: UnitEnv -> Maybe [UnitDatabase UnitId]
- GHC.Unit.Home.Graph: [homeUnitEnv_unit_dbs] :: HomeUnitEnv -> Maybe [UnitDatabase UnitId]
- GHC.Unit.State: [preloadClosure] :: UnitState -> PreloadUnitClosure
- GHC.Unit.State: [unwireMap] :: UnitState -> UniqMap UnitId UnitId
- GHC.Unit.State: [wireMap] :: UnitState -> UniqMap UnitId UnitId
- GHC.Unit.State: improveUnit :: UnitState -> Unit -> Unit
- GHC.Unit.State: instance GHC.Internal.Base.Monoid GHC.Unit.State.ModuleOrigin
- GHC.Unit.State: instance GHC.Internal.Base.Monoid GHC.Unit.State.UnitVisibility
- GHC.Unit.State: instance GHC.Internal.Base.Semigroup GHC.Unit.State.ModuleOrigin
- GHC.Unit.State: instance GHC.Internal.Base.Semigroup GHC.Unit.State.UnitVisibility
- GHC.Unit.State: instance GHC.Utils.Outputable.Outputable GHC.Unit.State.ModuleOrigin
- GHC.Unit.State: instance GHC.Utils.Outputable.Outputable GHC.Unit.State.UnitErr
- GHC.Unit.State: instance GHC.Utils.Outputable.Outputable GHC.Unit.State.UnitVisibility
- GHC.Unit.State: instance GHC.Utils.Outputable.Outputable GHC.Unit.State.UnusableUnitReason
- GHC.Unit.State: instance GHC.Utils.Outputable.Outputable u => GHC.Utils.Outputable.Outputable (GHC.Unit.State.UnitDatabase u)
- GHC.Unit.State: type PreloadUnitClosure = UniqSet UnitId
- GHC.Unit.State: type UnitInfoMap = UniqMap UnitId UnitInfo
- Language.Haskell.Syntax.Type: instance (GHC.Internal.Data.Data.Data rec, GHC.Internal.Data.Data.Data arg) => GHC.Internal.Data.Data.Data (Language.Haskell.Syntax.Type.HsConDetails arg rec)
+ GHC: Opt_GhciImportLoadedTargets :: GeneralFlag
+ GHC: [modBreaks_locs_] :: ModBreaks -> Array BreakTickIndex BinSrcSpan
+ GHC.Builtin.Names: unusedTypeTyConKey :: Unique
+ GHC.Builtin.PrimOps: PrimOpDecl :: FastString -> String -> PrimOpDoc
+ GHC.Builtin.PrimOps: PrimOpSection :: String -> String -> PrimOpDoc
+ GHC.Builtin.PrimOps: data PrimOpDoc
+ GHC.Builtin.Types: unusedTypeTyCon :: TyCon
+ GHC.ByteCode.Types: [modBreaks_locs_] :: ModBreaks -> Array BreakTickIndex BinSrcSpan
+ GHC.ByteCode.Types: mAX_SMALL_TUPLE_CTOI :: WordOff
+ GHC.Cmm.InitFini: isInitOrFiniSection :: SectionType -> Maybe InitOrFini
+ GHC.CmmToAsm.AArch64.Instr: SXTW :: Operand -> Operand -> Instr
+ GHC.CmmToAsm.Ppr: pprCOFFComdatKey :: IsLine doc => Platform -> CLabel -> doc
+ GHC.CmmToAsm.RV64.Instr: Dyn :: RoundingMode
+ GHC.CmmToAsm.RV64.Instr: Rdn :: RoundingMode
+ GHC.CmmToAsm.RV64.Instr: Rmm :: RoundingMode
+ GHC.CmmToAsm.RV64.Instr: Rne :: RoundingMode
+ GHC.CmmToAsm.RV64.Instr: Rtz :: RoundingMode
+ GHC.CmmToAsm.RV64.Instr: Rup :: RoundingMode
+ GHC.CmmToAsm.RV64.Instr: data RoundingMode
+ GHC.CmmToAsm.RV64.Regs: d28RegNo :: RegNo
+ GHC.CmmToAsm.RV64.Regs: ft11RegNo :: RegNo
+ GHC.CmmToAsm.RV64.Regs: ft8RegNo :: RegNo
+ GHC.CmmToAsm.Reg.Linear.Base: IgnoreFormat :: a -> IgnoreFormat a
+ GHC.CmmToAsm.Reg.Linear.Base: Loc :: VLoc -> Format -> Loc
+ GHC.CmmToAsm.Reg.Linear.Base: [locWithFormat_format] :: Loc -> Format
+ GHC.CmmToAsm.Reg.Linear.Base: [locWithFormat_loc] :: Loc -> VLoc
+ GHC.CmmToAsm.Reg.Linear.Base: data VLoc
+ GHC.CmmToAsm.Reg.Linear.Base: instance GHC.Internal.Classes.Eq (GHC.CmmToAsm.Reg.Linear.Base.IgnoreFormat GHC.CmmToAsm.Reg.Linear.Base.Loc)
+ GHC.CmmToAsm.Reg.Linear.Base: instance GHC.Internal.Classes.Eq GHC.CmmToAsm.Reg.Linear.Base.VLoc
+ GHC.CmmToAsm.Reg.Linear.Base: instance GHC.Internal.Classes.Ord (GHC.CmmToAsm.Reg.Linear.Base.IgnoreFormat GHC.CmmToAsm.Reg.Linear.Base.Loc)
+ GHC.CmmToAsm.Reg.Linear.Base: instance GHC.Internal.Classes.Ord GHC.CmmToAsm.Reg.Linear.Base.VLoc
+ GHC.CmmToAsm.Reg.Linear.Base: instance GHC.Internal.Show.Show GHC.CmmToAsm.Reg.Linear.Base.VLoc
+ GHC.CmmToAsm.Reg.Linear.Base: instance GHC.Utils.Outputable.Outputable GHC.CmmToAsm.Reg.Linear.Base.VLoc
+ GHC.CmmToAsm.Reg.Linear.Base: newtype IgnoreFormat a
+ GHC.CmmToAsm.Reg.Regs: Regs :: UniqSet RegWithFormat -> Regs
+ GHC.CmmToAsm.Reg.Regs: [getRegs] :: Regs -> UniqSet RegWithFormat
+ GHC.CmmToAsm.Reg.Regs: addRegMaxFmt :: Regs -> RegWithFormat -> Regs
+ GHC.CmmToAsm.Reg.Regs: addRegsMaxFmt :: Regs -> [RegWithFormat] -> Regs
+ GHC.CmmToAsm.Reg.Regs: elemRegs :: Reg -> Regs -> Bool
+ GHC.CmmToAsm.Reg.Regs: instance GHC.Internal.Classes.Eq GHC.CmmToAsm.Reg.Regs.Regs
+ GHC.CmmToAsm.Reg.Regs: instance GHC.Utils.Outputable.Outputable GHC.CmmToAsm.Reg.Regs.Regs
+ GHC.CmmToAsm.Reg.Regs: intersectRegsMaxFmt :: Regs -> Regs -> Regs
+ GHC.CmmToAsm.Reg.Regs: lookupReg :: Reg -> Regs -> Maybe Format
+ GHC.CmmToAsm.Reg.Regs: mapRegs :: (Reg -> Reg) -> Regs -> Regs
+ GHC.CmmToAsm.Reg.Regs: minusCoveredRegs :: Regs -> Regs -> Regs
+ GHC.CmmToAsm.Reg.Regs: minusRegs :: Regs -> Regs -> Regs
+ GHC.CmmToAsm.Reg.Regs: mkRegsMaxFmt :: [RegWithFormat] -> Regs
+ GHC.CmmToAsm.Reg.Regs: newtype Regs
+ GHC.CmmToAsm.Reg.Regs: noRegs :: Regs
+ GHC.CmmToAsm.Reg.Regs: shrinkingRegs :: Regs -> Regs -> Regs
+ GHC.CmmToAsm.Reg.Regs: unionManyRegsMaxFmt :: [Regs] -> Regs
+ GHC.CmmToAsm.Reg.Regs: unionRegsMaxFmt :: Regs -> Regs -> Regs
+ GHC.Core.Opt.Simplify.Env: SimplPhase :: CompilerPhase -> SimplPhase
+ GHC.Core.Opt.Simplify.Env: SimplPhaseRange :: CompilerPhase -> CompilerPhase -> SimplPhase
+ GHC.Core.Opt.Simplify.Env: data SimplPhase
+ GHC.Core.Opt.Simplify.Env: instance GHC.Internal.Classes.Eq GHC.Core.Opt.Simplify.Env.SimplPhase
+ GHC.Core.Opt.Simplify.Env: instance GHC.Utils.Outputable.Outputable GHC.Core.Opt.Simplify.Env.SimplPhase
+ GHC.Core.Opt.Simplify.Env: isActive :: SimplPhase -> Activation -> Bool
+ GHC.Core.Opt.Simplify.Env: simplEndPhase :: SimplPhase -> CompilerPhase
+ GHC.Core.Opt.Simplify.Env: simplStartPhase :: SimplPhase -> CompilerPhase
+ GHC.Core.Opt.Simplify.Utils: mkBottomCont :: StaticEnv -> SimplCont -> SimplCont
+ GHC.Core.Opt.Simplify.Utils: updModeForRuleLHS :: SimplMode -> SimplMode
+ GHC.Core.Opt.Simplify.Utils: updModeForRuleRHS :: Activation -> SimplMode -> SimplMode
+ GHC.Core.TyCon: isTerminatingTyCon :: TyCon -> Bool
+ GHC.Core.Utils: DoBinderSwap :: OutVar -> MCoercion -> BinderSwapDecision
+ GHC.Core.Utils: NoBinderSwap :: BinderSwapDecision
+ GHC.Core.Utils: data BinderSwapDecision
+ GHC.Core.Utils: mkTickCpe :: CoreTickish -> CoreExpr -> CoreExpr
+ GHC.Core.Utils: scrutOkForBinderSwap :: OutExpr -> BinderSwapDecision
+ GHC.Data.OsPath: createDirectoryIfMissing :: Bool -> OsPath -> IO ()
+ GHC.Data.OsPath: doesDirectoryExist :: OsPath -> IO Bool
+ GHC.Data.OsPath: doesFileExist :: OsPath -> IO Bool
+ GHC.Data.OsPath: dropTrailingPathSeparator :: OsPath -> OsPath
+ GHC.Data.OsPath: getDirectoryContents :: OsPath -> IO [OsPath]
+ GHC.Data.OsPath: isRelative :: OsPath -> Bool
+ GHC.Data.OsPath: isSuffixOf :: OsString -> OsString -> Bool
+ GHC.Data.OsPath: normalise :: OsPath -> OsPath
+ GHC.Data.OsPath: splitSearchPath :: OsString -> [OsPath]
+ GHC.Data.OsPath: takeDirectory :: OsPath -> OsPath
+ GHC.Driver.DynFlags: Opt_GhciImportLoadedTargets :: GeneralFlag
+ GHC.Driver.DynFlags: Opt_WarnSemaphoreOpenFailure :: WarningFlag
+ GHC.Driver.DynFlags: instance GHC.Internal.Classes.Ord GHC.Driver.DynFlags.ModRenaming
+ GHC.Driver.DynFlags: instance GHC.Internal.Classes.Ord GHC.Driver.DynFlags.PackageArg
+ GHC.Driver.DynFlags: instance GHC.Internal.Classes.Ord GHC.Driver.DynFlags.PackageDBFlag
+ GHC.Driver.DynFlags: instance GHC.Internal.Classes.Ord GHC.Driver.DynFlags.PackageFlag
+ GHC.Driver.DynFlags: instance GHC.Internal.Classes.Ord GHC.Driver.DynFlags.PkgDbRef
+ GHC.Driver.DynFlags: isPackageDbRef :: PackageDBFlag -> Maybe PkgDbRef
+ GHC.Driver.Env: hscEUD :: HscEnv -> IO (ExternalUnitDatabases UnitId)
+ GHC.Driver.Env: hscUIC :: HscEnv -> UnitIndexCache
+ GHC.Driver.Env: hscUnitIndex :: HscEnv -> IO UnitIndex
+ GHC.Driver.Errors.Types: [DriverSemaphoreOpenFailure] :: BuildingCabalPackage -> SemaphoreError -> DriverMessage
+ GHC.Driver.Flags: Opt_GhciImportLoadedTargets :: GeneralFlag
+ GHC.Driver.Flags: Opt_WarnSemaphoreOpenFailure :: WarningFlag
+ GHC.Driver.Session: Opt_GhciImportLoadedTargets :: GeneralFlag
+ GHC.Driver.Session: Opt_WarnSemaphoreOpenFailure :: WarningFlag
+ GHC.Hs.Binds: [aa_phase] :: ActivationAnn -> SourceText
+ GHC.HsToCore.Breakpoints: [modBreaks_locs_] :: ModBreaks -> Array BreakTickIndex BinSrcSpan
+ GHC.HsToCore.Breakpoints: modBreaks_locs :: ModBreaks -> Array BreakTickIndex SrcSpan
+ GHC.HsToCore.Breakpoints.Types: BreakpointId :: Module -> BreakTickIndex -> BreakpointId
+ GHC.HsToCore.Breakpoints.Types: ModBreaks :: Array BreakTickIndex BinSrcSpan -> Array BreakTickIndex [OccName] -> Array BreakTickIndex [String] -> Array BreakTickIndex (String, String) -> Module -> ModBreaks
+ GHC.HsToCore.Breakpoints.Types: [bi_tick_index] :: BreakpointId -> BreakTickIndex
+ GHC.HsToCore.Breakpoints.Types: [bi_tick_mod] :: BreakpointId -> Module
+ GHC.HsToCore.Breakpoints.Types: [modBreaks_ccs] :: ModBreaks -> Array BreakTickIndex (String, String)
+ GHC.HsToCore.Breakpoints.Types: [modBreaks_decls] :: ModBreaks -> Array BreakTickIndex [String]
+ GHC.HsToCore.Breakpoints.Types: [modBreaks_locs_] :: ModBreaks -> Array BreakTickIndex BinSrcSpan
+ GHC.HsToCore.Breakpoints.Types: [modBreaks_module] :: ModBreaks -> Module
+ GHC.HsToCore.Breakpoints.Types: [modBreaks_vars] :: ModBreaks -> Array BreakTickIndex [OccName]
+ GHC.HsToCore.Breakpoints.Types: data BreakpointId
+ GHC.HsToCore.Breakpoints.Types: data ModBreaks
+ GHC.HsToCore.Breakpoints.Types: instance Control.DeepSeq.NFData GHC.HsToCore.Breakpoints.Types.ModBreaks
+ GHC.HsToCore.Breakpoints.Types: instance GHC.Utils.Binary.Binary GHC.HsToCore.Breakpoints.Types.ModBreaks
+ GHC.HsToCore.Breakpoints.Types: modBreaks_locs :: ModBreaks -> Array BreakTickIndex SrcSpan
+ GHC.HsToCore.Breakpoints.Types: type BreakTickIndex = Int
+ GHC.Linker.Types: linkableAllBCOs :: Linkable -> [CompiledByteCode]
+ GHC.Platform: [pc_OFFSET_StgTSO_ctoi_tuple_spill_words] :: PlatformConstants -> Int
+ GHC.Platform.Constants: [pc_OFFSET_StgTSO_ctoi_tuple_spill_words] :: PlatformConstants -> Int
+ GHC.Rename.Env: lookupLocatedOccRnGRE :: WhatLooking -> GenLocated (EpAnn ann) RdrName -> TcRn (GenLocated (EpAnn ann) GlobalRdrElt)
+ GHC.Rename.Env: lookupOccRnGRE :: WhatLooking -> RdrName -> RnM GlobalRdrElt
+ GHC.Rename.Unbound: mkUnboundGREName :: Name -> GlobalRdrElt
+ GHC.Rename.Unbound: unboundGRE :: LookingFor -> RdrName -> RnM GlobalRdrElt
+ GHC.Rename.Unbound: unboundGREX :: LookingFor -> RdrName -> [GhcHint] -> RnM GlobalRdrElt
+ GHC.Runtime.Interpreter: [CustomMessage] :: Word8 -> ByteString -> Message ByteString
+ GHC.Runtime.Interpreter.Process: [CustomMessage] :: Word8 -> ByteString -> Message ByteString
+ GHC.Runtime.Interpreter.Types: [interpStringCache] :: Interp -> MVar (FastStringEnv (RemotePtr ()))
+ GHC.Stg.EnforceEpt.TagSig: TagBottoming :: TagInfo
+ GHC.Stg.EnforceEpt.TagSig: TagEPT :: TagInfo
+ GHC.Stg.EnforceEpt.TagSig: TagFun :: TagInfo -> TagSig
+ GHC.Stg.EnforceEpt.TagSig: TagVal :: TagInfo -> TagSig
+ GHC.Stg.EnforceEpt.TagSig: data TagSig
+ GHC.Stg.EnforceEpt.TagSig: isTaggedInfo :: TagInfo -> Bool
+ GHC.Stg.EnforceEpt.Types: argTagInfo :: Bool -> Maybe TagSig -> StgArg -> TagInfo
+ GHC.Stg.EnforceEpt.Types: lookupReturnInfo :: forall (p :: StgPass). TagEnv p -> Id -> Maybe TagInfo
+ GHC.StgToCmm.Config: [stgToCmmUseStdApThunk] :: StgToCmmConfig -> Bool
+ GHC.StgToCmm.Monad: [stgToCmmUseStdApThunk] :: StgToCmmConfig -> Bool
+ GHC.StgToJS.Regs: StgReg :: Int -> StgReg
+ GHC.StgToJS.Regs: highReg :: Int -> JStgExpr
+ GHC.StgToJS.Regs: highReg_expr :: JStgExpr -> JStgExpr
+ GHC.StgToJS.Regs: jsRegsFrom :: StgReg -> [JStgExpr]
+ GHC.StgToJS.Regs: lowRegsCount :: Int
+ GHC.StgToJS.Regs: lowRegsIdents :: [Ident]
+ GHC.StgToJS.Regs: maxLowReg :: StgReg
+ GHC.StgToJS.Regs: minHighReg :: StgReg
+ GHC.StgToJS.Regs: newtype StgReg
+ GHC.StgToJS.Regs: pattern R1 :: StgReg
+ GHC.StgToJS.Regs: pattern R2 :: StgReg
+ GHC.StgToJS.Regs: pattern R3 :: StgReg
+ GHC.StgToJS.Regs: pattern R4 :: StgReg
+ GHC.StgToJS.Regs: regNumber :: StgReg -> Int
+ GHC.StgToJS.Regs: regsFromTo :: StgReg -> StgReg -> [StgReg]
+ GHC.Tc.Errors.Types: [TcRnStaticFormWarning] :: [Name] -> TcRnMessage
+ GHC.Tc.Gen.Pat: zipPatsBndrs :: [LPat GhcRn] -> [TyVarBinder] -> TcM ([(HsTyPat GhcRn, TyVar)], [LPat GhcRn])
+ GHC.Tc.Types.Origin: foldMapCtOrigin :: Semigroup m => (CtOrigin -> m) -> CtOrigin -> m
+ GHC.Tc.Types.Origin: isHasFieldOrigin :: CtOrigin -> Bool
+ GHC.Tc.Utils.Monad: newUnusedType :: Name -> Kind -> TcM Type
+ GHC.Tc.Utils.TcMType: mkConcreteInfo :: ConcreteTvOrigin -> TcM MetaInfo
+ GHC.Tc.Utils.TcType: isUnusedTypeTy :: Type -> Bool
+ GHC.Types.Basic: earliestPhase :: CompilerPhase -> CompilerPhase -> CompilerPhase
+ GHC.Types.Basic: endPhase :: Activation -> CompilerPhase
+ GHC.Types.Basic: instance Control.DeepSeq.NFData GHC.Types.Basic.CompilerPhase
+ GHC.Types.Basic: instance GHC.Internal.Data.Data.Data GHC.Types.Basic.CompilerPhase
+ GHC.Types.Basic: instance GHC.Utils.Binary.Binary GHC.Types.Basic.CompilerPhase
+ GHC.Types.Basic: isActiveInPhase :: CompilerPhase -> Activation -> Bool
+ GHC.Types.Basic: laterThanPhase :: CompilerPhase -> CompilerPhase -> Bool
+ GHC.Types.Basic: latestPhase :: CompilerPhase -> CompilerPhase -> CompilerPhase
+ GHC.Types.Demand: lubDmdEnv :: DmdEnv -> DmdEnv -> DmdEnv
+ GHC.Types.Demand: maxCard :: Card -> Card -> Card
+ GHC.Types.Demand: maxDmd :: Demand -> Demand -> Demand
+ GHC.Types.Demand: maxDmdType :: DmdType -> DmdType -> DmdType
+ GHC.Types.Error: SuggestUpgradeForSemaphoreVersionMismatch :: SemaphoreUpgradeTarget -> Int -> GhcHint
+ GHC.Types.Error: jsonDiagnostic :: Diagnostic e => String -> MsgEnvelope e -> JsonDoc
+ GHC.Types.Hint: SuggestUpgradeForSemaphoreVersionMismatch :: SemaphoreUpgradeTarget -> Int -> GhcHint
+ GHC.Types.Hint: UpgradeCabalInstall :: SemaphoreUpgradeTarget
+ GHC.Types.Hint: UpgradeGHC :: SemaphoreUpgradeTarget
+ GHC.Types.Hint: UpgradeJobserver :: SemaphoreUpgradeTarget
+ GHC.Types.Hint: data SemaphoreUpgradeTarget
+ GHC.Types.Hint: instance GHC.Internal.Classes.Eq GHC.Types.Hint.SemaphoreUpgradeTarget
+ GHC.Types.Hint: instance GHC.Internal.Show.Show GHC.Types.Hint.SemaphoreUpgradeTarget
+ GHC.Types.Id.Info: mkDFunIdDetails :: Class -> IdDetails
+ GHC.Types.Name.Reader: unwrapUserRdr :: WithUserRdr a -> a
+ GHC.Types.Unique.FM: strictAddToUFM_C :: Uniquable key => (elt -> elt -> elt) -> UniqFM key elt -> key -> elt -> UniqFM key elt
+ GHC.Types.Unique.FM: strictIntersectUFM_C :: forall {k} elt1 elt2 elt3 (key :: k). (elt1 -> elt2 -> elt3) -> UniqFM key elt1 -> UniqFM key elt2 -> UniqFM key elt3
+ GHC.Types.Unique.FM: strictPlusUFM :: forall {k} (key :: k) elt. UniqFM key elt -> UniqFM key elt -> UniqFM key elt
+ GHC.Types.Unique.FM: strictPlusUFM_C :: forall {k} elt (key :: k). (elt -> elt -> elt) -> UniqFM key elt -> UniqFM key elt -> UniqFM key elt
+ GHC.Types.Unique.Set: minusUniqSet_C :: (a -> a -> Maybe a) -> UniqSet a -> UniqSet a -> UniqSet a
+ GHC.Types.Unique.Set: strictAddOneToUniqSet_C :: Uniquable a => (a -> a -> a) -> UniqSet a -> a -> UniqSet a
+ GHC.Types.Unique.Set: strictIntersectUniqSets_C :: (a -> a -> a) -> UniqSet a -> UniqSet a -> UniqSet a
+ GHC.Types.Unique.Set: strictUnionManyUniqSets_C :: (a -> a -> a) -> [UniqSet a] -> UniqSet a
+ GHC.Types.Unique.Set: strictUnionUniqSets_C :: (a -> a -> a) -> UniqSet a -> UniqSet a -> UniqSet a
+ GHC.Types.Var.Env: strictPlusVarEnv :: VarEnv a -> VarEnv a -> VarEnv a
+ GHC.Types.Var.Env: strictPlusVarEnv_C :: (a -> a -> a) -> VarEnv a -> VarEnv a -> VarEnv a
+ GHC.Unit.Env: [ue_uic] :: UnitEnv -> UnitIndexCache
+ GHC.Unit.Env: ueEUD :: UnitEnv -> IO (ExternalUnitDatabases UnitId)
+ GHC.Unit.Env: ueUI :: UnitEnv -> IO UnitIndex
+ GHC.Unit.External.Database: UnitDatabase :: OsPath -> [GenUnitInfo unit] -> UnitDatabase unit
+ GHC.Unit.External.Database: UnitDbConfig :: [PackageDBFlag] -> String -> FilePath -> ArchOS -> FilePath -> FilePath -> UnitDbConfig
+ GHC.Unit.External.Database: [unitDatabasePath] :: UnitDatabase unit -> OsPath
+ GHC.Unit.External.Database: [unitDatabaseUnits] :: UnitDatabase unit -> [GenUnitInfo unit]
+ GHC.Unit.External.Database: [unitDbConfigDBName] :: UnitDbConfig -> FilePath
+ GHC.Unit.External.Database: [unitDbConfigFlagsDB] :: UnitDbConfig -> [PackageDBFlag]
+ GHC.Unit.External.Database: [unitDbConfigGHCDir] :: UnitDbConfig -> FilePath
+ GHC.Unit.External.Database: [unitDbConfigGlobalDB] :: UnitDbConfig -> FilePath
+ GHC.Unit.External.Database: [unitDbConfigPlatformArchOS] :: UnitDbConfig -> ArchOS
+ GHC.Unit.External.Database: [unitDbConfigProgramName] :: UnitDbConfig -> String
+ GHC.Unit.External.Database: compareByPreference :: UnitPrecedenceMap -> UnitInfo -> UnitInfo -> Ordering
+ GHC.Unit.External.Database: data ExternalUnitDatabases unit
+ GHC.Unit.External.Database: data UnitDatabase unit
+ GHC.Unit.External.Database: data UnitDbConfig
+ GHC.Unit.External.Database: deleteExternalUnitDatabases :: OsPath -> ExternalUnitDatabases unit -> ExternalUnitDatabases unit
+ GHC.Unit.External.Database: emptyExternalUnitDatabases :: ExternalUnitDatabases unit
+ GHC.Unit.External.Database: getUnitDbRefs :: UnitDbConfig -> IO [PkgDbRef]
+ GHC.Unit.External.Database: insertExternalUnitDatabases :: UnitDatabase unit -> ExternalUnitDatabases unit -> ExternalUnitDatabases unit
+ GHC.Unit.External.Database: instance GHC.Internal.Classes.Eq GHC.Unit.External.Database.NormalisedUnitDbLoc
+ GHC.Unit.External.Database: instance GHC.Internal.Classes.Ord GHC.Unit.External.Database.NormalisedUnitDbLoc
+ GHC.Unit.External.Database: instance GHC.Utils.Outputable.Outputable u => GHC.Utils.Outputable.Outputable (GHC.Unit.External.Database.UnitDatabase u)
+ GHC.Unit.External.Database: lookupExternalUnitDatabases :: OsPath -> ExternalUnitDatabases unit -> Maybe (UnitDatabase unit)
+ GHC.Unit.External.Database: mergeDatabases :: Logger -> [UnitDatabase UnitId] -> IO (UnitInfoMap, UnitPrecedenceMap)
+ GHC.Unit.External.Database: readUnitDatabase :: Logger -> UnitDbConfig -> OsPath -> IO (UnitDatabase UnitId)
+ GHC.Unit.External.Database: resolveUnitDatabase :: UnitDbConfig -> PkgDbRef -> IO (Maybe OsPath)
+ GHC.Unit.External.Database: sortByPreference :: UnitPrecedenceMap -> [UnitInfo] -> [UnitInfo]
+ GHC.Unit.External.Database: type UnitPrecedenceMap = UniqMap UnitId Int
+ GHC.Unit.External.Index: UnitIndexCache :: IORef UnitIndex -> UnitIndexCache
+ GHC.Unit.External.Index: [uic_index] :: UnitIndexCache -> IORef UnitIndex
+ GHC.Unit.External.Index: addUnitInfoMap :: UnitInfoMap -> UnitIndex -> UnitIndex
+ GHC.Unit.External.Index: cacheExternalUnitDatabase :: UnitIndexCache -> UnitDatabase UnitId -> IO ()
+ GHC.Unit.External.Index: clearUnitIndexCache :: UnitIndexCache -> IO ()
+ GHC.Unit.External.Index: data GlobalUnitInfoMap
+ GHC.Unit.External.Index: data GlobalUnitKey
+ GHC.Unit.External.Index: data UnitIndex
+ GHC.Unit.External.Index: emptyGlobalUnitInfoMap :: GlobalUnitInfoMap
+ GHC.Unit.External.Index: emptyUnitIndex :: UnitIndex
+ GHC.Unit.External.Index: externalUnitDatabases :: UnitIndex -> ExternalUnitDatabases UnitId
+ GHC.Unit.External.Index: globalUnitKeyFromUnitInfo :: UnitInfo -> GlobalUnitKey
+ GHC.Unit.External.Index: globalUnits :: UnitIndex -> GlobalUnitInfoMap
+ GHC.Unit.External.Index: initUnitIndexCache :: IO UnitIndexCache
+ GHC.Unit.External.Index: lookupGlobalUnitInfoMap :: GlobalUnitKey -> GlobalUnitInfoMap -> Maybe UnitInfo
+ GHC.Unit.External.Index: mkGlobalUnitInfoMap :: [(UnitId, UnitInfo)] -> GlobalUnitInfoMap
+ GHC.Unit.External.Index: mkGlobalUnitKey :: UnitId -> UnitAbiHash -> GlobalUnitKey
+ GHC.Unit.External.Index: modifyUnitIndexCache :: UnitIndexCache -> (UnitIndex -> UnitIndex) -> IO ()
+ GHC.Unit.External.Index: newtype UnitIndexCache
+ GHC.Unit.External.Index: readExternalUnitDatabase :: UnitIndexCache -> OsPath -> IO (Maybe (UnitDatabase UnitId))
+ GHC.Unit.External.Index: readExternalUnitDatabases :: UnitIndexCache -> IO (ExternalUnitDatabases UnitId)
+ GHC.Unit.External.Index: readOrGetUnitDatabase :: Logger -> UnitIndexCache -> UnitDbConfig -> OsPath -> IO (UnitDatabase UnitId)
+ GHC.Unit.External.Index: readUnitDatabases :: Logger -> UnitIndexCache -> UnitDbConfig -> IO [UnitDatabase UnitId]
+ GHC.Unit.External.Index: readUnitIndex :: UnitIndexCache -> IO UnitIndex
+ GHC.Unit.External.Index: setWireMap :: WireMap -> UnitIndex -> UnitIndex
+ GHC.Unit.External.Index: setupWiredInUnits :: Logger -> UnitPrecedenceMap -> [UnitInfo] -> VisibilityMap -> UnitIndexCache -> IO WireMap
+ GHC.Unit.External.Index: type UnitAbiHash = ShortText
+ GHC.Unit.External.Index: unwireUnit :: UnitIndex -> Unit -> Unit
+ GHC.Unit.External.Index: unwiringMap :: UnitIndex -> UnwireMap
+ GHC.Unit.External.Index: updateWiredInUnitIdInModule :: WireMap -> Module -> Module
+ GHC.Unit.External.Index: updateWiredInUnitIndex :: WireMap -> [UnitInfo] -> UnitIndexCache -> IO [UnitInfo]
+ GHC.Unit.External.Index: updateWiredInUnits :: WireMap -> GlobalUnitInfoMap -> [UnitInfo] -> [Either UnitInfo UnitInfo]
+ GHC.Unit.External.Index: updateWiredInUnitsInUnitInfo :: WireMap -> GlobalUnitInfoMap -> UnitInfo -> Either UnitInfo UnitInfo
+ GHC.Unit.External.Index: wireMapExists :: UnitIndex -> Bool
+ GHC.Unit.External.Index: wiringMap :: UnitIndex -> WireMap
+ GHC.Unit.External.ModuleOrigin: ModHidden :: ModuleOrigin
+ GHC.Unit.External.ModuleOrigin: ModOrigin :: Maybe Bool -> [UnitInfo] -> [UnitInfo] -> Bool -> ModuleOrigin
+ GHC.Unit.External.ModuleOrigin: ModUnusable :: UnusableUnit -> ModuleOrigin
+ GHC.Unit.External.ModuleOrigin: [fromExposedReexport] :: ModuleOrigin -> [UnitInfo]
+ GHC.Unit.External.ModuleOrigin: [fromHiddenReexport] :: ModuleOrigin -> [UnitInfo]
+ GHC.Unit.External.ModuleOrigin: [fromOrigUnit] :: ModuleOrigin -> Maybe Bool
+ GHC.Unit.External.ModuleOrigin: [fromPackageFlag] :: ModuleOrigin -> Bool
+ GHC.Unit.External.ModuleOrigin: data ModuleOrigin
+ GHC.Unit.External.ModuleOrigin: fromExposedModules :: Bool -> ModuleOrigin
+ GHC.Unit.External.ModuleOrigin: fromFlag :: ModuleOrigin
+ GHC.Unit.External.ModuleOrigin: fromReexportedModules :: Bool -> UnitInfo -> ModuleOrigin
+ GHC.Unit.External.ModuleOrigin: instance GHC.Internal.Base.Monoid GHC.Unit.External.ModuleOrigin.ModuleOrigin
+ GHC.Unit.External.ModuleOrigin: instance GHC.Internal.Base.Semigroup GHC.Unit.External.ModuleOrigin.ModuleOrigin
+ GHC.Unit.External.ModuleOrigin: instance GHC.Utils.Outputable.Outputable GHC.Unit.External.ModuleOrigin.ModuleOrigin
+ GHC.Unit.External.ModuleOrigin: originEmpty :: ModuleOrigin -> Bool
+ GHC.Unit.External.ModuleOrigin: originVisible :: ModuleOrigin -> Bool
+ GHC.Unit.External.Providers: mkModuleNameProvidersMap :: Logger -> Bool -> UnitInfoMap -> VisibilityMap -> ModuleNameProvidersMap
+ GHC.Unit.External.Providers: mkUnusableModuleNameProvidersMap :: UnusableUnits -> ModuleNameProvidersMap
+ GHC.Unit.External.Providers: pprModuleMap :: ModuleNameProvidersMap -> SDoc
+ GHC.Unit.External.Providers: type ModuleNameProvidersMap = UniqMap ModuleName UniqMap Module ModuleOrigin
+ GHC.Unit.External.Query: lookupUnit' :: Bool -> UnitInfoMap -> Unit -> Maybe UnitInfo
+ GHC.Unit.External.Query: lookupUnitId' :: UnitInfoMap -> UnitId -> Maybe UnitInfo
+ GHC.Unit.External.Substitution: renameHoleModule' :: UnitInfoMap -> ShHoleSubst -> Module -> Module
+ GHC.Unit.External.Substitution: renameHoleUnit' :: UnitInfoMap -> ShHoleSubst -> Unit -> Unit
+ GHC.Unit.External.Substitution: renameUnitInfo :: UnitInfoMap -> [(ModuleName, Module)] -> UnitInfo -> UnitInfo
+ GHC.Unit.External.Substitution: type ShHoleSubst = ModuleNameEnv Module
+ GHC.Unit.External.Validate: BrokenDependencies :: [UnitId] -> UnusableUnitReason
+ GHC.Unit.External.Validate: CloseUnitErr :: UnitId -> Maybe UnitId -> UnitErr
+ GHC.Unit.External.Validate: CyclicDependencies :: [UnitId] -> UnusableUnitReason
+ GHC.Unit.External.Validate: IgnoredDependencies :: [UnitId] -> UnusableUnitReason
+ GHC.Unit.External.Validate: IgnoredWithFlag :: UnusableUnitReason
+ GHC.Unit.External.Validate: PackageFlagErr :: PackageFlag -> [(UnitInfo, UnusableUnitReason)] -> UnitErr
+ GHC.Unit.External.Validate: ShadowedDependencies :: [UnitId] -> UnusableUnitReason
+ GHC.Unit.External.Validate: TrustFlagErr :: TrustFlag -> [(UnitInfo, UnusableUnitReason)] -> UnitErr
+ GHC.Unit.External.Validate: UnusableUnit :: Unit -> UnusableUnitReason -> Bool -> UnusableUnit
+ GHC.Unit.External.Validate: [uuIsReexport] :: UnusableUnit -> Bool
+ GHC.Unit.External.Validate: [uuReason] :: UnusableUnit -> UnusableUnitReason
+ GHC.Unit.External.Validate: [uuUnit] :: UnusableUnit -> Unit
+ GHC.Unit.External.Validate: closeUnitDeps :: UnitInfoMap -> [(UnitId, Maybe UnitId)] -> MaybeErr UnitErr [UnitId]
+ GHC.Unit.External.Validate: closeUnitDeps' :: UnitInfoMap -> [UnitId] -> [(UnitId, Maybe UnitId)] -> MaybeErr UnitErr [UnitId]
+ GHC.Unit.External.Validate: data UnitErr
+ GHC.Unit.External.Validate: data UnusableUnit
+ GHC.Unit.External.Validate: data UnusableUnitReason
+ GHC.Unit.External.Validate: findPackages :: UnitPrecedenceMap -> UnitInfoMap -> PackageArg -> [UnitInfo] -> UnusableUnits -> Either [(UnitInfo, UnusableUnitReason)] [UnitInfo]
+ GHC.Unit.External.Validate: ignoreUnits :: [IgnorePackageFlag] -> [UnitInfo] -> UnusableUnits
+ GHC.Unit.External.Validate: instance GHC.Utils.Outputable.Outputable GHC.Unit.External.Validate.UnitErr
+ GHC.Unit.External.Validate: instance GHC.Utils.Outputable.Outputable GHC.Unit.External.Validate.UnusableUnitReason
+ GHC.Unit.External.Validate: mayThrowUnitErr :: MaybeErr UnitErr a -> IO a
+ GHC.Unit.External.Validate: pprFlag :: PackageFlag -> SDoc
+ GHC.Unit.External.Validate: pprReason :: SDoc -> UnusableUnitReason -> SDoc
+ GHC.Unit.External.Validate: reportUnusable :: Logger -> UnusableUnits -> IO ()
+ GHC.Unit.External.Validate: selectPackages :: UnitPrecedenceMap -> PackageArg -> [UnitInfo] -> UnusableUnits -> Either [(UnitInfo, UnusableUnitReason)] ([UnitInfo], [UnitInfo])
+ GHC.Unit.External.Validate: type UnusableUnits = UniqMap UnitId (UnitInfo, UnusableUnitReason)
+ GHC.Unit.External.Validate: validateDatabase :: [IgnorePackageFlag] -> UnitInfoMap -> (UnitInfoMap, UnusableUnits, [SCC UnitInfo])
+ GHC.Unit.External.Visibility: UnitVisibility :: Bool -> [(ModuleName, ModuleName)] -> First FastString -> UniqMap ModuleName (Set InstantiatedModule) -> Maybe PackageArg -> UnitVisibility
+ GHC.Unit.External.Visibility: [uv_explicit] :: UnitVisibility -> Maybe PackageArg
+ GHC.Unit.External.Visibility: [uv_expose_all] :: UnitVisibility -> Bool
+ GHC.Unit.External.Visibility: [uv_package_name] :: UnitVisibility -> First FastString
+ GHC.Unit.External.Visibility: [uv_renamings] :: UnitVisibility -> [(ModuleName, ModuleName)]
+ GHC.Unit.External.Visibility: [uv_requirements] :: UnitVisibility -> UniqMap ModuleName (Set InstantiatedModule)
+ GHC.Unit.External.Visibility: data UnitVisibility
+ GHC.Unit.External.Visibility: instance GHC.Internal.Base.Monoid GHC.Unit.External.Visibility.UnitVisibility
+ GHC.Unit.External.Visibility: instance GHC.Internal.Base.Semigroup GHC.Unit.External.Visibility.UnitVisibility
+ GHC.Unit.External.Visibility: instance GHC.Utils.Outputable.Outputable GHC.Unit.External.Visibility.UnitVisibility
+ GHC.Unit.External.Visibility: type VisibilityMap = UniqMap Unit UnitVisibility
+ GHC.Unit.External.Wired: data UnwireMap
+ GHC.Unit.External.Wired: data WireMap
+ GHC.Unit.External.Wired: emptyUnwireMap :: UnwireMap
+ GHC.Unit.External.Wired: emptyWireMap :: WireMap
+ GHC.Unit.External.Wired: findWiredInUnits :: Logger -> UnitPrecedenceMap -> [UnitInfo] -> VisibilityMap -> IO WireMap
+ GHC.Unit.External.Wired: isWireMapEmpty :: WireMap -> Bool
+ GHC.Unit.External.Wired: listWireMap :: WireMap -> [(UnitId, UnitId)]
+ GHC.Unit.External.Wired: lookupUnwireMap :: UnitId -> UnwireMap -> Maybe UnitId
+ GHC.Unit.External.Wired: lookupWireMap :: UnitId -> WireMap -> Maybe UnitId
+ GHC.Unit.External.Wired: nonDetFoldWireMap :: ((UnitId, UnitId) -> b -> b) -> b -> WireMap -> b
+ GHC.Unit.External.Wired: unwiringMapFromWireMap :: WireMap -> UnwireMap
+ GHC.Unit.Info: evaluateUnitInfoLists :: UnitInfo -> IO UnitInfo
+ GHC.Unit.Info: mkUnitInfoMap :: [UnitInfo] -> UnitInfoMap
+ GHC.Unit.Info: seqUnitInfoLists :: UnitInfo -> b -> b
+ GHC.Unit.Info: type UnitInfoMap = UniqMap UnitId UnitInfo
+ GHC.Unit.Module.Deps: stableUsageCmp :: Usage -> Usage -> Ordering
+ GHC.Unit.Module.Graph: [mg_home_module_name_providers_map] :: ModuleGraph -> HomeModuleNameProvidersMap
+ GHC.Unit.Module.Graph: mgHomeModuleNameProvidersMap :: ModuleGraph -> HomeModuleNameProvidersMap
+ GHC.Unit.Module.Graph: type HomeModuleNameProvidersMap = UniqMap ModuleName Set UnitId
+ GHC.Unit.Module.ModIface: [mi_sc_modBreaks] :: IfaceSimplifiedCore -> Maybe ModBreaks
+ GHC.Unit.Module.WholeCoreBindings: [wcb_modBreaks] :: WholeCoreBindings -> Maybe ModBreaks
+ GHC.Unit.State: Distrusted :: IsTrusted
+ GHC.Unit.State: Trusted :: IsTrusted
+ GHC.Unit.State: [trustedUnits] :: UnitState -> TrustOverlay
+ GHC.Unit.State: data IsTrusted
+ GHC.Unit.State: data TrustOverlay
+ GHC.Unit.State: distrustUnits :: [UnitId] -> TrustOverlay -> TrustOverlay
+ GHC.Unit.State: emptyTrustOverlay :: TrustOverlay
+ GHC.Unit.State: instance GHC.Internal.Classes.Eq GHC.Unit.State.IsTrusted
+ GHC.Unit.State: instance GHC.Internal.Classes.Ord GHC.Unit.State.IsTrusted
+ GHC.Unit.State: isUnitIdTrusted :: HasDebugCallStack => UnitState -> UnitId -> Bool
+ GHC.Unit.State: isUnitInfoTrusted :: HasDebugCallStack => UnitState -> UnitInfo -> Bool
+ GHC.Unit.State: isUnitTrusted :: HasDebugCallStack => UnitState -> Unit -> Bool
+ GHC.Unit.State: lookupTrustOverlay :: TrustOverlay -> UnitId -> Maybe IsTrusted
+ GHC.Unit.State: selectHptFlag :: Set UnitId -> PackageFlag -> Bool
+ GHC.Unit.State: trustUnits :: [UnitId] -> TrustOverlay -> TrustOverlay
+ GHC.Utils.Binary: instance Control.DeepSeq.NFData GHC.Utils.Binary.BinSrcSpan
+ GHC.Utils.Logger: decorateDiagnostic :: LogFlags -> MessageClass -> SrcSpan -> SDoc -> IO SDoc
+ GHC.Utils.Outputable: instance GHC.Utils.Outputable.Outputable System.OsPath.Types.OsPath
+ Language.Haskell.Syntax.Type: instance (GHC.Internal.Data.Data.Data arg, GHC.Internal.Data.Data.Data rec) => GHC.Internal.Data.Data.Data (Language.Haskell.Syntax.Type.HsConDetails arg rec)
- GHC: DynFlags :: GhcMode -> GhcLink -> Backend -> GhcNameVersion -> FileSettings -> UnitSettings -> Platform -> ToolSettings -> PlatformMisc -> [(String, String)] -> TempDir -> Int -> Int -> Int -> Int -> Int -> Maybe String -> [Int] -> Maybe ParMakeCount -> Bool -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Int -> Int -> Int -> Int -> Int -> Maybe Int -> Maybe Int -> Int -> Maybe Word -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Bool -> Maybe Int -> Int -> [FilePath] -> ModuleName -> Maybe String -> IntWithInf -> IntWithInf -> Int -> Int -> Int -> UnitId -> Maybe UnitId -> [(ModuleName, Module)] -> Maybe FilePath -> Maybe String -> Set ModuleName -> [ReexportedModule] -> Ways -> Maybe (String, Int) -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> String -> String -> String -> String -> String -> String -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> DynLibLoader -> Bool -> FilePath -> Maybe FilePath -> [Option] -> IncludeSpecs -> [String] -> [String] -> [String] -> Maybe String -> RtsOptsEnabled -> Bool -> String -> [ModuleName] -> [(ModuleName, String)] -> [String] -> [ExternalPluginSpec] -> FilePath -> Bool -> Bool -> [ModuleName] -> [String] -> [PackageDBFlag] -> [IgnorePackageFlag] -> [PackageFlag] -> [PackageFlag] -> [TrustFlag] -> Maybe FilePath -> EnumSet DumpFlag -> EnumSet GeneralFlag -> EnumSet WarningFlag -> EnumSet WarningFlag -> WarningCategorySet -> WarningCategorySet -> Maybe Language -> SafeHaskellMode -> Bool -> Bool -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> [OnOff Extension] -> EnumSet Extension -> UnfoldingOpts -> Int -> Int -> Int -> String -> Int -> Maybe String -> Maybe String -> Maybe String -> FlushOut -> Maybe FilePath -> Maybe String -> [String] -> Int -> Int -> Bool -> OverridingBool -> Bool -> OverridingBool -> Bool -> Scheme -> ProfAuto -> [CallerCcFilter] -> Maybe String -> Maybe SseVersion -> Maybe BmiVersion -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Int -> Int -> Int -> Bool -> Maybe Int -> Word64 -> Int -> Weights -> DynFlags
+ GHC: DynFlags :: GhcMode -> GhcLink -> Backend -> GhcNameVersion -> FileSettings -> UnitSettings -> Platform -> ToolSettings -> PlatformMisc -> [(String, String)] -> TempDir -> Int -> Int -> Int -> Int -> Int -> Maybe String -> [Int] -> Maybe ParMakeCount -> Bool -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Int -> Int -> Int -> Int -> Int -> Maybe Int -> Maybe Int -> Int -> Maybe Word -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Bool -> Maybe Int -> Int -> [FilePath] -> ModuleName -> Maybe String -> IntWithInf -> IntWithInf -> Int -> Int -> Int -> UnitId -> Maybe UnitId -> [(ModuleName, Module)] -> Maybe FilePath -> Maybe String -> UniqSet ModuleName -> [ReexportedModule] -> Ways -> Maybe (String, Int) -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> String -> String -> String -> String -> String -> String -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> DynLibLoader -> Bool -> FilePath -> Maybe FilePath -> [Option] -> IncludeSpecs -> [String] -> [String] -> [String] -> Maybe String -> RtsOptsEnabled -> Bool -> String -> [ModuleName] -> [(ModuleName, String)] -> [String] -> [ExternalPluginSpec] -> FilePath -> Bool -> Bool -> [ModuleName] -> [String] -> [PackageDBFlag] -> [IgnorePackageFlag] -> [PackageFlag] -> [PackageFlag] -> [TrustFlag] -> Maybe FilePath -> EnumSet DumpFlag -> EnumSet GeneralFlag -> EnumSet WarningFlag -> EnumSet WarningFlag -> WarningCategorySet -> WarningCategorySet -> Maybe Language -> SafeHaskellMode -> Bool -> Bool -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> [OnOff Extension] -> EnumSet Extension -> UnfoldingOpts -> Int -> Int -> Int -> String -> Int -> Maybe String -> Maybe String -> Maybe String -> FlushOut -> Maybe FilePath -> Maybe String -> [String] -> Int -> Int -> Bool -> OverridingBool -> Bool -> OverridingBool -> Bool -> Scheme -> ProfAuto -> [CallerCcFilter] -> Maybe String -> Maybe SseVersion -> Maybe BmiVersion -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Int -> Int -> Int -> Bool -> Maybe Int -> Word64 -> Int -> Weights -> DynFlags
- GHC: ModBreaks :: Array BreakTickIndex SrcSpan -> Array BreakTickIndex [OccName] -> Array BreakTickIndex [String] -> Array BreakTickIndex (String, String) -> Module -> ModBreaks
+ GHC: ModBreaks :: Array BreakTickIndex BinSrcSpan -> Array BreakTickIndex [OccName] -> Array BreakTickIndex [String] -> Array BreakTickIndex (String, String) -> Module -> ModBreaks
- GHC: [hiddenModules] :: DynFlags -> Set ModuleName
+ GHC: [hiddenModules] :: DynFlags -> UniqSet ModuleName
- GHC.Builtin.PrimOps: primOpDocs :: [(FastString, String)]
+ GHC.Builtin.PrimOps: primOpDocs :: [PrimOpDoc]
- GHC.ByteCode.Types: ModBreaks :: Array BreakTickIndex SrcSpan -> Array BreakTickIndex [OccName] -> Array BreakTickIndex [String] -> Array BreakTickIndex (String, String) -> Module -> ModBreaks
+ GHC.ByteCode.Types: ModBreaks :: Array BreakTickIndex BinSrcSpan -> Array BreakTickIndex [OccName] -> Array BreakTickIndex [String] -> Array BreakTickIndex (String, String) -> Module -> ModBreaks
- GHC.Cmm: sectionProtection :: Section -> SectionProtection
+ GHC.Cmm: sectionProtection :: SectionType -> SectionProtection
- GHC.Cmm.MachOp: machOpArgReps :: Platform -> MachOp -> [Width]
+ GHC.Cmm.MachOp: machOpArgReps :: Platform -> MachOp -> Maybe [Width]
- GHC.CmmToAsm.RV64.Instr: FCVT :: FcvtVariant -> Operand -> Operand -> Instr
+ GHC.CmmToAsm.RV64.Instr: FCVT :: FcvtVariant -> Operand -> Operand -> RoundingMode -> Instr
- GHC.CmmToAsm.Reg.Linear.Base: InBoth :: RealRegUsage -> StackSlot -> Loc
+ GHC.CmmToAsm.Reg.Linear.Base: InBoth :: RealReg -> StackSlot -> VLoc
- GHC.CmmToAsm.Reg.Linear.Base: InMem :: StackSlot -> Loc
+ GHC.CmmToAsm.Reg.Linear.Base: InMem :: StackSlot -> VLoc
- GHC.CmmToAsm.Reg.Linear.Base: InReg :: RealRegUsage -> Loc
+ GHC.CmmToAsm.Reg.Linear.Base: InReg :: RealReg -> VLoc
- GHC.CmmToAsm.Reg.Linear.Base: regsOfLoc :: Loc -> [RealRegUsage]
+ GHC.CmmToAsm.Reg.Linear.Base: regsOfLoc :: VLoc -> [RealReg]
- GHC.CmmToAsm.Reg.Linear.JoinToTargets: joinToTargets :: (FR freeRegs, Instruction instr) => BlockMap (UniqSet RegWithFormat) -> BlockId -> instr -> RegM freeRegs ([NatBasicBlock instr], instr)
+ GHC.CmmToAsm.Reg.Linear.JoinToTargets: joinToTargets :: (FR freeRegs, Instruction instr) => BlockMap Regs -> BlockId -> instr -> RegM freeRegs ([NatBasicBlock instr], instr)
- GHC.CmmToAsm.Reg.Linear.StackMap: StackMap :: Int -> UniqFM Unique StackSlot -> StackMap
+ GHC.CmmToAsm.Reg.Linear.StackMap: StackMap :: Int -> UniqFM Unique (StackSlot, Int) -> StackMap
- GHC.CmmToAsm.Reg.Linear.StackMap: [stackMapAssignment] :: StackMap -> UniqFM Unique StackSlot
+ GHC.CmmToAsm.Reg.Linear.StackMap: [stackMapAssignment] :: StackMap -> UniqFM Unique (StackSlot, Int)
- GHC.CmmToAsm.Reg.Liveness: LiveInfo :: LabelMap RawCmmStatics -> [BlockId] -> BlockMap (UniqSet RegWithFormat) -> BlockMap IntSet -> LiveInfo
+ GHC.CmmToAsm.Reg.Liveness: LiveInfo :: LabelMap RawCmmStatics -> [BlockId] -> BlockMap Regs -> BlockMap IntSet -> LiveInfo
- GHC.CmmToAsm.Reg.Liveness: Liveness :: UniqSet RegWithFormat -> UniqSet RegWithFormat -> UniqSet RegWithFormat -> Liveness
+ GHC.CmmToAsm.Reg.Liveness: Liveness :: Regs -> Regs -> Regs -> Liveness
- GHC.CmmToAsm.Reg.Liveness: [liveBorn] :: Liveness -> UniqSet RegWithFormat
+ GHC.CmmToAsm.Reg.Liveness: [liveBorn] :: Liveness -> Regs
- GHC.CmmToAsm.Reg.Liveness: [liveDieRead] :: Liveness -> UniqSet RegWithFormat
+ GHC.CmmToAsm.Reg.Liveness: [liveDieRead] :: Liveness -> Regs
- GHC.CmmToAsm.Reg.Liveness: [liveDieWrite] :: Liveness -> UniqSet RegWithFormat
+ GHC.CmmToAsm.Reg.Liveness: [liveDieWrite] :: Liveness -> Regs
- GHC.CmmToAsm.Reg.Liveness: slurpConflicts :: Instruction instr => Platform -> LiveCmmDecl statics instr -> (Bag (UniqSet RegWithFormat), Bag (Reg, Reg))
+ GHC.CmmToAsm.Reg.Liveness: slurpConflicts :: Instruction instr => Platform -> LiveCmmDecl statics instr -> (Bag Regs, Bag (Reg, Reg))
- GHC.CmmToLlvm.Config: LlvmCgConfig :: Platform -> SDocContext -> Bool -> Bool -> Bool -> Maybe BmiVersion -> Maybe LlvmVersion -> Bool -> String -> LlvmConfig -> LlvmCgConfig
+ GHC.CmmToLlvm.Config: LlvmCgConfig :: Platform -> SDocContext -> Bool -> Bool -> Maybe BmiVersion -> Maybe LlvmVersion -> Bool -> String -> LlvmConfig -> LlvmCgConfig
- GHC.Core.Opt.Simplify.Env: SimplMode :: CompilerPhase -> [String] -> Bool -> Bool -> Bool -> Bool -> UnfoldingOpts -> Bool -> Bool -> FloatEnable -> Bool -> ArityOpts -> RuleOpts -> Bool -> Bool -> OptCoercionOpts -> SimplMode
+ GHC.Core.Opt.Simplify.Env: SimplMode :: SimplPhase -> [String] -> Bool -> Bool -> Bool -> Bool -> UnfoldingOpts -> Bool -> Bool -> FloatEnable -> Bool -> ArityOpts -> RuleOpts -> Bool -> Bool -> OptCoercionOpts -> SimplMode
- GHC.Core.Opt.Simplify.Env: [sm_phase] :: SimplMode -> CompilerPhase
+ GHC.Core.Opt.Simplify.Env: [sm_phase] :: SimplMode -> SimplPhase
- GHC.Core.Opt.Simplify.Env: sePhase :: SimplEnv -> CompilerPhase
+ GHC.Core.Opt.Simplify.Env: sePhase :: SimplEnv -> SimplPhase
- GHC.Core.Opt.WorkWrap.Utils: mkAbsentFiller :: WwOpts -> Id -> StrictnessMark -> Maybe CoreExpr
+ GHC.Core.Opt.WorkWrap.Utils: mkAbsentFiller :: Module -> Id -> StrictnessMark -> Maybe CoreExpr
- GHC.Core.Utils: mergeCaseAlts :: Id -> [CoreAlt] -> Maybe ([CoreBind], [CoreAlt])
+ GHC.Core.Utils: mergeCaseAlts :: CoreExpr -> Id -> [CoreAlt] -> Maybe ([CoreBind], [CoreAlt])
- GHC.Driver.Config.Finder: FinderOpts :: [OsPath] -> Bool -> Bool -> Ways -> Bool -> Maybe OsPath -> Maybe FastString -> Set ModuleName -> Map ModuleName ModuleName -> Maybe OsPath -> OsString -> Maybe OsPath -> OsString -> OsString -> Maybe OsPath -> OsString -> OsString -> Maybe OsPath -> FinderOpts
+ GHC.Driver.Config.Finder: FinderOpts :: [OsPath] -> Bool -> Bool -> Ways -> Bool -> Maybe OsPath -> Maybe FastString -> UniqSet ModuleName -> UniqMap ModuleName ModuleName -> Maybe OsPath -> OsString -> Maybe OsPath -> OsString -> OsString -> Maybe OsPath -> OsString -> OsString -> Maybe OsPath -> FinderOpts
- GHC.Driver.Config.Finder: [finder_hiddenModules] :: FinderOpts -> Set ModuleName
+ GHC.Driver.Config.Finder: [finder_hiddenModules] :: FinderOpts -> UniqSet ModuleName
- GHC.Driver.Config.Finder: [finder_reexportedModules] :: FinderOpts -> Map ModuleName ModuleName
+ GHC.Driver.Config.Finder: [finder_reexportedModules] :: FinderOpts -> UniqMap ModuleName ModuleName
- GHC.Driver.DynFlags: DynFlags :: GhcMode -> GhcLink -> Backend -> GhcNameVersion -> FileSettings -> UnitSettings -> Platform -> ToolSettings -> PlatformMisc -> [(String, String)] -> TempDir -> Int -> Int -> Int -> Int -> Int -> Maybe String -> [Int] -> Maybe ParMakeCount -> Bool -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Int -> Int -> Int -> Int -> Int -> Maybe Int -> Maybe Int -> Int -> Maybe Word -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Bool -> Maybe Int -> Int -> [FilePath] -> ModuleName -> Maybe String -> IntWithInf -> IntWithInf -> Int -> Int -> Int -> UnitId -> Maybe UnitId -> [(ModuleName, Module)] -> Maybe FilePath -> Maybe String -> Set ModuleName -> [ReexportedModule] -> Ways -> Maybe (String, Int) -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> String -> String -> String -> String -> String -> String -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> DynLibLoader -> Bool -> FilePath -> Maybe FilePath -> [Option] -> IncludeSpecs -> [String] -> [String] -> [String] -> Maybe String -> RtsOptsEnabled -> Bool -> String -> [ModuleName] -> [(ModuleName, String)] -> [String] -> [ExternalPluginSpec] -> FilePath -> Bool -> Bool -> [ModuleName] -> [String] -> [PackageDBFlag] -> [IgnorePackageFlag] -> [PackageFlag] -> [PackageFlag] -> [TrustFlag] -> Maybe FilePath -> EnumSet DumpFlag -> EnumSet GeneralFlag -> EnumSet WarningFlag -> EnumSet WarningFlag -> WarningCategorySet -> WarningCategorySet -> Maybe Language -> SafeHaskellMode -> Bool -> Bool -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> [OnOff Extension] -> EnumSet Extension -> UnfoldingOpts -> Int -> Int -> Int -> String -> Int -> Maybe String -> Maybe String -> Maybe String -> FlushOut -> Maybe FilePath -> Maybe String -> [String] -> Int -> Int -> Bool -> OverridingBool -> Bool -> OverridingBool -> Bool -> Scheme -> ProfAuto -> [CallerCcFilter] -> Maybe String -> Maybe SseVersion -> Maybe BmiVersion -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Int -> Int -> Int -> Bool -> Maybe Int -> Word64 -> Int -> Weights -> DynFlags
+ GHC.Driver.DynFlags: DynFlags :: GhcMode -> GhcLink -> Backend -> GhcNameVersion -> FileSettings -> UnitSettings -> Platform -> ToolSettings -> PlatformMisc -> [(String, String)] -> TempDir -> Int -> Int -> Int -> Int -> Int -> Maybe String -> [Int] -> Maybe ParMakeCount -> Bool -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Int -> Int -> Int -> Int -> Int -> Maybe Int -> Maybe Int -> Int -> Maybe Word -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Bool -> Maybe Int -> Int -> [FilePath] -> ModuleName -> Maybe String -> IntWithInf -> IntWithInf -> Int -> Int -> Int -> UnitId -> Maybe UnitId -> [(ModuleName, Module)] -> Maybe FilePath -> Maybe String -> UniqSet ModuleName -> [ReexportedModule] -> Ways -> Maybe (String, Int) -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> String -> String -> String -> String -> String -> String -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> DynLibLoader -> Bool -> FilePath -> Maybe FilePath -> [Option] -> IncludeSpecs -> [String] -> [String] -> [String] -> Maybe String -> RtsOptsEnabled -> Bool -> String -> [ModuleName] -> [(ModuleName, String)] -> [String] -> [ExternalPluginSpec] -> FilePath -> Bool -> Bool -> [ModuleName] -> [String] -> [PackageDBFlag] -> [IgnorePackageFlag] -> [PackageFlag] -> [PackageFlag] -> [TrustFlag] -> Maybe FilePath -> EnumSet DumpFlag -> EnumSet GeneralFlag -> EnumSet WarningFlag -> EnumSet WarningFlag -> WarningCategorySet -> WarningCategorySet -> Maybe Language -> SafeHaskellMode -> Bool -> Bool -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> [OnOff Extension] -> EnumSet Extension -> UnfoldingOpts -> Int -> Int -> Int -> String -> Int -> Maybe String -> Maybe String -> Maybe String -> FlushOut -> Maybe FilePath -> Maybe String -> [String] -> Int -> Int -> Bool -> OverridingBool -> Bool -> OverridingBool -> Bool -> Scheme -> ProfAuto -> [CallerCcFilter] -> Maybe String -> Maybe SseVersion -> Maybe BmiVersion -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Int -> Int -> Int -> Bool -> Maybe Int -> Word64 -> Int -> Weights -> DynFlags
- GHC.Driver.DynFlags: PkgDbPath :: FilePath -> PkgDbRef
+ GHC.Driver.DynFlags: PkgDbPath :: OsPath -> PkgDbRef
- GHC.Driver.DynFlags: [hiddenModules] :: DynFlags -> Set ModuleName
+ GHC.Driver.DynFlags: [hiddenModules] :: DynFlags -> UniqSet ModuleName
- GHC.Driver.Main: hscSimpleIface' :: Maybe CoreProgram -> TcGblEnv -> ModSummary -> Hsc (ModIface, ModDetails)
+ GHC.Driver.Main: hscSimpleIface' :: Maybe CoreProgram -> Maybe ModBreaks -> TcGblEnv -> ModSummary -> Hsc (ModIface, ModDetails)
- GHC.Driver.MakeAction: JSemLimit :: SemaphoreName -> WorkerLimit
+ GHC.Driver.MakeAction: JSemLimit :: SemaphoreIdentifier -> WorkerLimit
- GHC.Driver.MakeAction: runWorkerLimit :: WorkerLimit -> (AbstractSem -> IO a) -> IO a
+ GHC.Driver.MakeAction: runWorkerLimit :: Logger -> DynFlags -> WorkerLimit -> (AbstractSem -> IO a) -> IO a
- GHC.Driver.MakeSem: runJSemAbstractSem :: SemaphoreName -> (AbstractSem -> IO a) -> IO a
+ GHC.Driver.MakeSem: runJSemAbstractSem :: SemaphoreIdentifier -> (AbstractSem -> IO a) -> IO a
- GHC.Driver.Pipeline.Execute: llvmOptions :: LlvmConfig -> DynFlags -> [(String, String)]
+ GHC.Driver.Pipeline.Execute: llvmOptions :: LlvmConfig -> Maybe LlvmVersion -> DynFlags -> [(String, String)]
- GHC.Driver.Session: DynFlags :: GhcMode -> GhcLink -> Backend -> GhcNameVersion -> FileSettings -> UnitSettings -> Platform -> ToolSettings -> PlatformMisc -> [(String, String)] -> TempDir -> Int -> Int -> Int -> Int -> Int -> Maybe String -> [Int] -> Maybe ParMakeCount -> Bool -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Int -> Int -> Int -> Int -> Int -> Maybe Int -> Maybe Int -> Int -> Maybe Word -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Bool -> Maybe Int -> Int -> [FilePath] -> ModuleName -> Maybe String -> IntWithInf -> IntWithInf -> Int -> Int -> Int -> UnitId -> Maybe UnitId -> [(ModuleName, Module)] -> Maybe FilePath -> Maybe String -> Set ModuleName -> [ReexportedModule] -> Ways -> Maybe (String, Int) -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> String -> String -> String -> String -> String -> String -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> DynLibLoader -> Bool -> FilePath -> Maybe FilePath -> [Option] -> IncludeSpecs -> [String] -> [String] -> [String] -> Maybe String -> RtsOptsEnabled -> Bool -> String -> [ModuleName] -> [(ModuleName, String)] -> [String] -> [ExternalPluginSpec] -> FilePath -> Bool -> Bool -> [ModuleName] -> [String] -> [PackageDBFlag] -> [IgnorePackageFlag] -> [PackageFlag] -> [PackageFlag] -> [TrustFlag] -> Maybe FilePath -> EnumSet DumpFlag -> EnumSet GeneralFlag -> EnumSet WarningFlag -> EnumSet WarningFlag -> WarningCategorySet -> WarningCategorySet -> Maybe Language -> SafeHaskellMode -> Bool -> Bool -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> [OnOff Extension] -> EnumSet Extension -> UnfoldingOpts -> Int -> Int -> Int -> String -> Int -> Maybe String -> Maybe String -> Maybe String -> FlushOut -> Maybe FilePath -> Maybe String -> [String] -> Int -> Int -> Bool -> OverridingBool -> Bool -> OverridingBool -> Bool -> Scheme -> ProfAuto -> [CallerCcFilter] -> Maybe String -> Maybe SseVersion -> Maybe BmiVersion -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Int -> Int -> Int -> Bool -> Maybe Int -> Word64 -> Int -> Weights -> DynFlags
+ GHC.Driver.Session: DynFlags :: GhcMode -> GhcLink -> Backend -> GhcNameVersion -> FileSettings -> UnitSettings -> Platform -> ToolSettings -> PlatformMisc -> [(String, String)] -> TempDir -> Int -> Int -> Int -> Int -> Int -> Maybe String -> [Int] -> Maybe ParMakeCount -> Bool -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Int -> Int -> Int -> Int -> Int -> Maybe Int -> Maybe Int -> Int -> Maybe Word -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Bool -> Maybe Int -> Int -> [FilePath] -> ModuleName -> Maybe String -> IntWithInf -> IntWithInf -> Int -> Int -> Int -> UnitId -> Maybe UnitId -> [(ModuleName, Module)] -> Maybe FilePath -> Maybe String -> UniqSet ModuleName -> [ReexportedModule] -> Ways -> Maybe (String, Int) -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> String -> String -> String -> String -> String -> String -> Maybe String -> Maybe String -> Maybe String -> Maybe String -> DynLibLoader -> Bool -> FilePath -> Maybe FilePath -> [Option] -> IncludeSpecs -> [String] -> [String] -> [String] -> Maybe String -> RtsOptsEnabled -> Bool -> String -> [ModuleName] -> [(ModuleName, String)] -> [String] -> [ExternalPluginSpec] -> FilePath -> Bool -> Bool -> [ModuleName] -> [String] -> [PackageDBFlag] -> [IgnorePackageFlag] -> [PackageFlag] -> [PackageFlag] -> [TrustFlag] -> Maybe FilePath -> EnumSet DumpFlag -> EnumSet GeneralFlag -> EnumSet WarningFlag -> EnumSet WarningFlag -> WarningCategorySet -> WarningCategorySet -> Maybe Language -> SafeHaskellMode -> Bool -> Bool -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> SrcSpan -> [OnOff Extension] -> EnumSet Extension -> UnfoldingOpts -> Int -> Int -> Int -> String -> Int -> Maybe String -> Maybe String -> Maybe String -> FlushOut -> Maybe FilePath -> Maybe String -> [String] -> Int -> Int -> Bool -> OverridingBool -> Bool -> OverridingBool -> Bool -> Scheme -> ProfAuto -> [CallerCcFilter] -> Maybe String -> Maybe SseVersion -> Maybe BmiVersion -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Int -> Int -> Int -> Bool -> Maybe Int -> Word64 -> Int -> Weights -> DynFlags
- GHC.Driver.Session: PkgDbPath :: FilePath -> PkgDbRef
+ GHC.Driver.Session: PkgDbPath :: OsPath -> PkgDbRef
- GHC.Driver.Session: [hiddenModules] :: DynFlags -> Set ModuleName
+ GHC.Driver.Session: [hiddenModules] :: DynFlags -> UniqSet ModuleName
- GHC.Hs.Binds: ActivationAnn :: EpToken "[" -> EpToken "]" -> Maybe (EpToken "~") -> Maybe EpaLocation -> ActivationAnn
+ GHC.Hs.Binds: ActivationAnn :: EpToken "[" -> SourceText -> EpToken "]" -> Maybe (EpToken "~") -> Maybe EpaLocation -> ActivationAnn
- GHC.HsToCore.Breakpoints: ModBreaks :: Array BreakTickIndex SrcSpan -> Array BreakTickIndex [OccName] -> Array BreakTickIndex [String] -> Array BreakTickIndex (String, String) -> Module -> ModBreaks
+ GHC.HsToCore.Breakpoints: ModBreaks :: Array BreakTickIndex BinSrcSpan -> Array BreakTickIndex [OccName] -> Array BreakTickIndex [String] -> Array BreakTickIndex (String, String) -> Module -> ModBreaks
- GHC.HsToCore.Match: matchWrapper :: HsMatchContextRn -> Maybe [LHsExpr GhcTc] -> MatchGroup GhcTc (LHsExpr GhcTc) -> DsM ([Id], CoreExpr)
+ GHC.HsToCore.Match: matchWrapper :: HsMatchContextRn -> Maybe [CoreExpr] -> MatchGroup GhcTc (LHsExpr GhcTc) -> DsM ([Id], CoreExpr)
- GHC.Iface.Errors.Types: GenericMissing :: [(Unit, Maybe UnitInfo)] -> [Unit] -> [UnusableUnit] -> [FilePath] -> CantFindInstalledReason
+ GHC.Iface.Errors.Types: GenericMissing :: [UnitInfo] -> [Unit] -> [UnusableUnit] -> [FilePath] -> CantFindInstalledReason
- GHC.Iface.Make: mkIfaceTc :: HscEnv -> SafeHaskellMode -> ModDetails -> ModSummary -> Maybe CoreProgram -> TcGblEnv -> IO ModIface
+ GHC.Iface.Make: mkIfaceTc :: HscEnv -> SafeHaskellMode -> ModDetails -> ModSummary -> Maybe CoreProgram -> Maybe ModBreaks -> TcGblEnv -> IO ModIface
- GHC.Platform: PlatformConstants :: Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Integer -> Integer -> Integer -> Bool -> PlatformConstants
+ GHC.Platform: PlatformConstants :: Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Integer -> Integer -> Integer -> Bool -> PlatformConstants
- GHC.Platform.Constants: PlatformConstants :: Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Integer -> Integer -> Integer -> Bool -> PlatformConstants
+ GHC.Platform.Constants: PlatformConstants :: Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Integer -> Integer -> Integer -> Bool -> PlatformConstants
- GHC.Rename.Env: lookupTypeOccRn :: RdrName -> RnM Name
+ GHC.Rename.Env: lookupTypeOccRn :: RdrName -> RnM GlobalRdrElt
- GHC.Rename.HsType: rnLTyVar :: LocatedN RdrName -> RnM (LocatedN Name)
+ GHC.Rename.HsType: rnLTyVar :: LocatedN RdrName -> RnM (LocatedN GlobalRdrElt)
- GHC.Rename.Splice: checkThLocalName :: Bool -> LIdOccP GhcRn -> RnM (HsExpr GhcRn)
+ GHC.Rename.Splice: checkThLocalName :: Bool -> LocatedN (WithUserRdr GlobalRdrElt) -> RnM (HsExpr GhcRn)
- GHC.Rename.Splice: checkThLocalNameNoLift :: LIdOccP GhcRn -> RnM ()
+ GHC.Rename.Splice: checkThLocalNameNoLift :: LocatedN (WithUserRdr GlobalRdrElt) -> RnM ()
- GHC.Rename.Splice: checkThLocalNameWithLift :: LIdOccP GhcRn -> RnM (HsExpr GhcRn)
+ GHC.Rename.Splice: checkThLocalNameWithLift :: LocatedN (WithUserRdr GlobalRdrElt) -> RnM (HsExpr GhcRn)
- GHC.Rename.Splice: checkThLocalTyName :: Name -> RnM ()
+ GHC.Rename.Splice: checkThLocalTyName :: GlobalRdrElt -> RnM ()
- GHC.Runtime.Interpreter.Types: Interp :: InterpInstance -> Loader -> InterpSymbolCache -> Interp
+ GHC.Runtime.Interpreter.Types: Interp :: InterpInstance -> Loader -> InterpSymbolCache -> MVar (FastStringEnv (RemotePtr ())) -> Interp
- GHC.Stg.EnforceEpt.Rewrite: rewriteTopBinds :: Module -> UniqSupply -> [GenStgTopBinding 'InferTaggedBinders] -> [TgStgTopBinding]
+ GHC.Stg.EnforceEpt.Rewrite: rewriteTopBinds :: Bool -> Module -> UniqSupply -> [GenStgTopBinding 'InferTaggedBinders] -> [TgStgTopBinding]
- GHC.StgToCmm.Utils: emitRtsCallGen :: [(LocalReg, ForeignHint)] -> CLabel -> [(CmmExpr, ForeignHint)] -> Bool -> FCode ()
+ GHC.StgToCmm.Utils: emitRtsCallGen :: [(LocalReg, ForeignHint)] -> CLabel -> CmmReturnInfo -> [(CmmExpr, ForeignHint)] -> Bool -> FCode ()
- GHC.StgToJS.Regs: lowRegs :: [Ident]
+ GHC.StgToJS.Regs: lowRegs :: [StgReg]
- GHC.StgToJS.Regs: maxReg :: Int
+ GHC.StgToJS.Regs: maxReg :: StgReg
- GHC.StgToJS.Regs: minReg :: Int
+ GHC.StgToJS.Regs: minReg :: StgReg
- GHC.SysTools.Terminal: stderrSupportsAnsiColors :: Bool
+ GHC.SysTools.Terminal: stderrSupportsAnsiColors :: IO Bool
- GHC.Tc.Errors.Types: LevelCheckSplice :: Name -> Maybe GlobalRdrElt -> LevelCheckReason
+ GHC.Tc.Errors.Types: LevelCheckSplice :: WithUserRdr GlobalRdrElt -> LevelCheckReason
- GHC.Tc.Plugin: NotFound :: [FilePath] -> Maybe Unit -> [Unit] -> [Unit] -> [UnusableUnit] -> [ModuleSuggestion] -> FindResult
+ GHC.Tc.Plugin: NotFound :: [FilePath] -> Maybe Unit -> [Unit] -> [UnitInfo] -> [UnusableUnit] -> [ModuleSuggestion] -> FindResult
- GHC.Tc.Plugin: [fr_pkgs_hidden] :: FindResult -> [Unit]
+ GHC.Tc.Plugin: [fr_pkgs_hidden] :: FindResult -> [UnitInfo]
- GHC.Tc.Utils.Env: LevelCheckSplice :: Name -> Maybe GlobalRdrElt -> LevelCheckReason
+ GHC.Tc.Utils.Env: LevelCheckSplice :: WithUserRdr GlobalRdrElt -> LevelCheckReason
- GHC.Tc.Utils.Monad: getCurrentAndBindLevel :: Name -> TcRn (Maybe (TopLevelFlag, Set ThLevelIndex, ThLevel))
+ GHC.Tc.Utils.Monad: getCurrentAndBindLevel :: GlobalRdrElt -> TcRn (Maybe (TopLevelFlag, Set ThLevelIndex, ThLevel))
- GHC.Types.Basic: ActiveAfter :: SourceText -> PhaseNum -> Activation
+ GHC.Types.Basic: ActiveAfter :: PhaseNum -> Activation
- GHC.Types.Basic: ActiveBefore :: SourceText -> PhaseNum -> Activation
+ GHC.Types.Basic: ActiveBefore :: PhaseNum -> Activation
- GHC.Types.Name.Reader: userRdrName :: WithUserRdr Name -> RdrName
+ GHC.Types.Name.Reader: userRdrName :: WithUserRdr a -> RdrName
- GHC.Unit.Env: HomeUnitEnv :: UnitState -> Maybe [UnitDatabase UnitId] -> DynFlags -> HomePackageTable -> Maybe HomeUnit -> HomeUnitEnv
+ GHC.Unit.Env: HomeUnitEnv :: UnitState -> DynFlags -> HomePackageTable -> Maybe HomeUnit -> HomeUnitEnv
- GHC.Unit.Env: UnitEnv :: ExternalUnitCache -> UnitId -> ModuleGraph -> HomeUnitGraph -> Platform -> GhcNameVersion -> UnitEnv
+ GHC.Unit.Env: UnitEnv :: ExternalUnitCache -> UnitId -> ModuleGraph -> HomeUnitGraph -> Platform -> GhcNameVersion -> UnitIndexCache -> UnitEnv
- GHC.Unit.Finder: FinderOpts :: [OsPath] -> Bool -> Bool -> Ways -> Bool -> Maybe OsPath -> Maybe FastString -> Set ModuleName -> Map ModuleName ModuleName -> Maybe OsPath -> OsString -> Maybe OsPath -> OsString -> OsString -> Maybe OsPath -> OsString -> OsString -> Maybe OsPath -> FinderOpts
+ GHC.Unit.Finder: FinderOpts :: [OsPath] -> Bool -> Bool -> Ways -> Bool -> Maybe OsPath -> Maybe FastString -> UniqSet ModuleName -> UniqMap ModuleName ModuleName -> Maybe OsPath -> OsString -> Maybe OsPath -> OsString -> OsString -> Maybe OsPath -> OsString -> OsString -> Maybe OsPath -> FinderOpts
- GHC.Unit.Finder: NotFound :: [FilePath] -> Maybe Unit -> [Unit] -> [Unit] -> [UnusableUnit] -> [ModuleSuggestion] -> FindResult
+ GHC.Unit.Finder: NotFound :: [FilePath] -> Maybe Unit -> [Unit] -> [UnitInfo] -> [UnusableUnit] -> [ModuleSuggestion] -> FindResult
- GHC.Unit.Finder: [finder_hiddenModules] :: FinderOpts -> Set ModuleName
+ GHC.Unit.Finder: [finder_hiddenModules] :: FinderOpts -> UniqSet ModuleName
- GHC.Unit.Finder: [finder_reexportedModules] :: FinderOpts -> Map ModuleName ModuleName
+ GHC.Unit.Finder: [finder_reexportedModules] :: FinderOpts -> UniqMap ModuleName ModuleName
- GHC.Unit.Finder: [fr_pkgs_hidden] :: FindResult -> [Unit]
+ GHC.Unit.Finder: [fr_pkgs_hidden] :: FindResult -> [UnitInfo]
- GHC.Unit.Finder.Types: FinderOpts :: [OsPath] -> Bool -> Bool -> Ways -> Bool -> Maybe OsPath -> Maybe FastString -> Set ModuleName -> Map ModuleName ModuleName -> Maybe OsPath -> OsString -> Maybe OsPath -> OsString -> OsString -> Maybe OsPath -> OsString -> OsString -> Maybe OsPath -> FinderOpts
+ GHC.Unit.Finder.Types: FinderOpts :: [OsPath] -> Bool -> Bool -> Ways -> Bool -> Maybe OsPath -> Maybe FastString -> UniqSet ModuleName -> UniqMap ModuleName ModuleName -> Maybe OsPath -> OsString -> Maybe OsPath -> OsString -> OsString -> Maybe OsPath -> OsString -> OsString -> Maybe OsPath -> FinderOpts
- GHC.Unit.Finder.Types: NotFound :: [FilePath] -> Maybe Unit -> [Unit] -> [Unit] -> [UnusableUnit] -> [ModuleSuggestion] -> FindResult
+ GHC.Unit.Finder.Types: NotFound :: [FilePath] -> Maybe Unit -> [Unit] -> [UnitInfo] -> [UnusableUnit] -> [ModuleSuggestion] -> FindResult
- GHC.Unit.Finder.Types: [finder_hiddenModules] :: FinderOpts -> Set ModuleName
+ GHC.Unit.Finder.Types: [finder_hiddenModules] :: FinderOpts -> UniqSet ModuleName
- GHC.Unit.Finder.Types: [finder_reexportedModules] :: FinderOpts -> Map ModuleName ModuleName
+ GHC.Unit.Finder.Types: [finder_reexportedModules] :: FinderOpts -> UniqMap ModuleName ModuleName
- GHC.Unit.Finder.Types: [fr_pkgs_hidden] :: FindResult -> [Unit]
+ GHC.Unit.Finder.Types: [fr_pkgs_hidden] :: FindResult -> [UnitInfo]
- GHC.Unit.Home.Graph: HomeUnitEnv :: UnitState -> Maybe [UnitDatabase UnitId] -> DynFlags -> HomePackageTable -> Maybe HomeUnit -> HomeUnitEnv
+ GHC.Unit.Home.Graph: HomeUnitEnv :: UnitState -> DynFlags -> HomePackageTable -> Maybe HomeUnit -> HomeUnitEnv
- GHC.Unit.Home.Graph: mkHomeUnitEnv :: UnitState -> Maybe [UnitDatabase UnitId] -> DynFlags -> HomePackageTable -> Maybe HomeUnit -> HomeUnitEnv
+ GHC.Unit.Home.Graph: mkHomeUnitEnv :: UnitState -> DynFlags -> HomePackageTable -> Maybe HomeUnit -> HomeUnitEnv
- GHC.Unit.Module.Graph: ModuleGraph :: [ModuleGraphNode] -> (ReachabilityIndex SummaryNode, NodeKey -> Maybe SummaryNode) -> (ReachabilityIndex SummaryNode, NodeKey -> Maybe SummaryNode) -> (ReachabilityIndex ZeroSummaryNode, ZeroScopeKey -> Maybe ZeroSummaryNode) -> Bool -> ModuleGraph
+ GHC.Unit.Module.Graph: ModuleGraph :: [ModuleGraphNode] -> (ReachabilityIndex SummaryNode, NodeKey -> Maybe SummaryNode) -> (ReachabilityIndex SummaryNode, NodeKey -> Maybe SummaryNode) -> (ReachabilityIndex ZeroSummaryNode, ZeroScopeKey -> Maybe ZeroSummaryNode) -> Bool -> HomeModuleNameProvidersMap -> ModuleGraph
- GHC.Unit.Module.ModIface: IfaceSimplifiedCore :: [IfaceBindingX IfaceMaybeRhs IfaceTopBndrInfo] -> IfaceForeign -> IfaceSimplifiedCore
+ GHC.Unit.Module.ModIface: IfaceSimplifiedCore :: [IfaceBindingX IfaceMaybeRhs IfaceTopBndrInfo] -> Maybe ModBreaks -> IfaceForeign -> IfaceSimplifiedCore
- GHC.Unit.Module.WholeCoreBindings: WholeCoreBindings :: [IfaceBindingX IfaceMaybeRhs IfaceTopBndrInfo] -> Module -> ModLocation -> IfaceForeign -> WholeCoreBindings
+ GHC.Unit.Module.WholeCoreBindings: WholeCoreBindings :: [IfaceBindingX IfaceMaybeRhs IfaceTopBndrInfo] -> Maybe ModBreaks -> Module -> ModLocation -> IfaceForeign -> WholeCoreBindings
- GHC.Unit.State: LookupHidden :: [(Module, ModuleOrigin)] -> [(Module, ModuleOrigin)] -> LookupResult
+ GHC.Unit.State: LookupHidden :: [UnitInfo] -> [(Module, ModuleOrigin)] -> LookupResult
- GHC.Unit.State: UnitDatabase :: FilePath -> [GenUnitInfo unit] -> UnitDatabase unit
+ GHC.Unit.State: UnitDatabase :: OsPath -> [GenUnitInfo unit] -> UnitDatabase unit
- GHC.Unit.State: UnitState :: UnitInfoMap -> PreloadUnitClosure -> UniqFM PackageName UnitId -> UniqMap UnitId UnitId -> UniqMap UnitId UnitId -> [UnitId] -> [(Unit, Maybe PackageArg)] -> [UnitId] -> ModuleNameProvidersMap -> ModuleNameProvidersMap -> UniqMap ModuleName [InstantiatedModule] -> Bool -> UnitState
+ GHC.Unit.State: UnitState :: UnitInfoMap -> TrustOverlay -> UniqFM PackageName UnitId -> [UnitId] -> [(Unit, Maybe PackageArg)] -> Set UnitId -> ModuleNameProvidersMap -> ModuleNameProvidersMap -> UniqMap ModuleName [InstantiatedModule] -> Bool -> UnitState
- GHC.Unit.State: [homeUnitDepends] :: UnitState -> [UnitId]
+ GHC.Unit.State: [homeUnitDepends] :: UnitState -> Set UnitId
- GHC.Unit.State: [unitDatabasePath] :: UnitDatabase unit -> FilePath
+ GHC.Unit.State: [unitDatabasePath] :: UnitDatabase unit -> OsPath
- GHC.Unit.State: getUnitDbRefs :: UnitConfig -> IO [PkgDbRef]
+ GHC.Unit.State: getUnitDbRefs :: UnitDbConfig -> IO [PkgDbRef]
- GHC.Unit.State: initUnits :: Logger -> DynFlags -> Maybe [UnitDatabase UnitId] -> Set UnitId -> IO ([UnitDatabase UnitId], UnitState, HomeUnit, Maybe PlatformConstants)
+ GHC.Unit.State: initUnits :: Logger -> DynFlags -> UnitIndexCache -> Set UnitId -> IO (UnitState, HomeUnit, Maybe PlatformConstants)
- GHC.Unit.State: instModuleToModule :: UnitState -> InstantiatedModule -> Module
+ GHC.Unit.State: instModuleToModule :: InstantiatedModule -> Module
- GHC.Unit.State: instUnitToUnit :: UnitState -> InstantiatedUnit -> Unit
+ GHC.Unit.State: instUnitToUnit :: InstantiatedUnit -> Unit
- GHC.Unit.State: lookupUnit' :: Bool -> UnitInfoMap -> PreloadUnitClosure -> Unit -> Maybe UnitInfo
+ GHC.Unit.State: lookupUnit' :: Bool -> UnitInfoMap -> Unit -> Maybe UnitInfo
- GHC.Unit.State: readUnitDatabase :: Logger -> UnitConfig -> FilePath -> IO (UnitDatabase UnitId)
+ GHC.Unit.State: readUnitDatabase :: Logger -> UnitDbConfig -> OsPath -> IO (UnitDatabase UnitId)
- GHC.Unit.State: readUnitDatabases :: Logger -> UnitConfig -> IO [UnitDatabase UnitId]
+ GHC.Unit.State: readUnitDatabases :: Logger -> UnitIndexCache -> UnitDbConfig -> IO [UnitDatabase UnitId]
- GHC.Unit.State: renameHoleModule' :: UnitInfoMap -> PreloadUnitClosure -> ShHoleSubst -> Module -> Module
+ GHC.Unit.State: renameHoleModule' :: UnitInfoMap -> ShHoleSubst -> Module -> Module
- GHC.Unit.State: renameHoleUnit' :: UnitInfoMap -> PreloadUnitClosure -> ShHoleSubst -> Unit -> Unit
+ GHC.Unit.State: renameHoleUnit' :: UnitInfoMap -> ShHoleSubst -> Unit -> Unit
- GHC.Unit.State: resolveUnitDatabase :: UnitConfig -> PkgDbRef -> IO (Maybe FilePath)
+ GHC.Unit.State: resolveUnitDatabase :: UnitDbConfig -> PkgDbRef -> IO (Maybe OsPath)
- GHC.Unit.State: unwireUnit :: UnitState -> Unit -> Unit
+ GHC.Unit.State: unwireUnit :: UnitIndex -> Unit -> Unit
- GHC.Utils.Logger: logJsonMsg :: ToJson a => Logger -> MessageClass -> a -> IO ()
+ GHC.Utils.Logger: logJsonMsg :: Logger -> MessageClass -> JsonDoc -> IO ()
- GHC.Utils.Misc: modificationTimeIfExists :: FilePath -> IO (Maybe UTCTime)
+ GHC.Utils.Misc: modificationTimeIfExists :: OsPath -> IO (Maybe UTCTime)

Files

Bytecodes.h view
@@ -23,6 +23,11 @@    I hope that's clear :-) */ +/*+   Make sure to update jumptable in rts/Interpreter.c when modifying+   bytecodes! See Note [Instruction dispatch in the bytecode interpreter]+   for details.+*/ #define bci_STKCHECK                    1 #define bci_PUSH_L                      2 #define bci_PUSH_LL                     3@@ -226,5 +231,11 @@    rendering an explicit check unnecessary in the majority of    cases. */ #define INTERP_STACK_CHECK_THRESH 50++/* Maximum nativeCallStackSpillSize for which we use a small stg_ctoi_tN+   frame (no old_spill slot, no TSO access) instead of the generic+   stg_ctoi_t frame.  Must match the stg_ctoi_tN definitions in+   StgMiscClosures.cmm. */+#define MAX_SMALL_TUPLE_CTOI    8  /*-------------------------------------------------------------------------*/
GHC.hs view
@@ -378,6 +378,7 @@ import GHC.Builtin.Types.Prim ( alphaTyVars ) import GHC.Data.StringBuffer import GHC.Data.FastString+import GHC.Data.FastString.Env import qualified GHC.LanguageExtensions as LangExt import GHC.Rename.Names (renamePkgQual, renameRawPkgQual) @@ -663,15 +664,12 @@   logger <- getLogger   hsc_env <- getSession -  let old_hue = ue_findHomeUnitEnv uid (hsc_unit_env hsc_env)-  let cached_unit_dbs = homeUnitEnv_unit_dbs old_hue-  (dbs,unit_state,home_unit,mconstants) <- liftIO $ initUnits logger dflags1 cached_unit_dbs (hsc_all_home_unit_ids hsc_env)+  (unit_state,home_unit,mconstants) <- liftIO $ initUnits logger dflags1 (hscUIC hsc_env) (hsc_all_home_unit_ids hsc_env)   updated_dflags <- liftIO $ updatePlatformConstants dflags1 mconstants    let upd hue =        hue           { homeUnitEnv_units = unit_state-          , homeUnitEnv_unit_dbs = Just dbs           , homeUnitEnv_dflags = updated_dflags           , homeUnitEnv_home_unit = Just home_unit           }@@ -714,6 +712,8 @@   logger  <- getLogger   lookup_cache  <- liftIO $ mkInterpSymbolCache +  fs_cache <- liftIO $ newMVar emptyFsEnv+   -- see Note [Target code interpreter]   interp <- if     -- Wasm dynamic linker@@ -746,7 +746,7 @@                   wasmInterpHsSoSuffix = way_tag ++ dynLibSuffix (ghcNameVersion dflags),                   wasmInterpUnitState = ue_homeUnitState $ hsc_unit_env hsc_env                 }-        pure $ Just $ Interp (ExternalInterp $ ExtWasm $ ExtInterpState cfg s) loader lookup_cache+        pure $ Just $ Interp (ExternalInterp $ ExtWasm $ ExtInterpState cfg s) loader lookup_cache fs_cache      -- JavaScript interpreter     | ArchJavaScript <- platformArch (targetPlatform dflags)@@ -764,7 +764,7 @@               , jsInterpFinderOpts  = initFinderOpts dflags               , jsInterpFinderCache = hsc_FC hsc_env               }-         return (Just (Interp (ExternalInterp (ExtJS (ExtInterpState cfg s))) loader lookup_cache))+         return (Just (Interp (ExternalInterp (ExtJS (ExtInterpState cfg s))) loader lookup_cache fs_cache))      -- external interpreter     | gopt Opt_ExternalInterpreter dflags@@ -793,7 +793,7 @@             }          s <- liftIO $ newMVar InterpPending          loader <- liftIO Loader.uninitializedLoader-         return (Just (Interp (ExternalInterp (ExtIServ (ExtInterpState conf s))) loader lookup_cache))+         return (Just (Interp (ExternalInterp (ExtIServ (ExtInterpState conf s))) loader lookup_cache fs_cache))      -- Internal interpreter     | otherwise@@ -801,7 +801,7 @@ #if defined(HAVE_INTERNAL_INTERPRETER)      do       loader <- liftIO Loader.uninitializedLoader-      return (Just (Interp InternalInterp loader lookup_cache))+      return (Just (Interp InternalInterp loader lookup_cache fs_cache)) #else       return Nothing #endif@@ -835,17 +835,15 @@         old_unit_env <- ue_setFlags dflags0 . hsc_unit_env <$> getSession          home_unit_graph <- forM (ue_home_unit_graph old_unit_env) $ \homeUnitEnv -> do-          let cached_unit_dbs = homeUnitEnv_unit_dbs homeUnitEnv-              dflags = homeUnitEnv_dflags homeUnitEnv+          let dflags = homeUnitEnv_dflags homeUnitEnv               old_hpt = homeUnitEnv_hpt homeUnitEnv               home_units = HUG.allUnits (ue_home_unit_graph old_unit_env) -          (dbs,unit_state,home_unit,mconstants) <- liftIO $ initUnits logger dflags cached_unit_dbs home_units+          (unit_state,home_unit,mconstants) <- liftIO $ initUnits logger dflags (ue_uic old_unit_env) home_units            updated_dflags <- liftIO $ updatePlatformConstants dflags0 mconstants           pure HomeUnitEnv             { homeUnitEnv_units = unit_state-            , homeUnitEnv_unit_dbs = Just dbs             , homeUnitEnv_dflags = updated_dflags             , homeUnitEnv_hpt = old_hpt             , homeUnitEnv_home_unit = Just home_unit@@ -859,6 +857,7 @@               , ue_current_unit    = ue_currentUnit old_unit_env               , ue_module_graph    = ue_module_graph old_unit_env               , ue_eps             = ue_eps old_unit_env+              , ue_uic      = ue_uic old_unit_env               }         modifySession $ \h -> hscSetFlags dflags1 h{ hsc_unit_env = unit_env }     else modifySession (hscSetFlags dflags0)@@ -916,6 +915,7 @@             , ue_current_unit    = ue_currentUnit unit_env0             , ue_eps             = ue_eps unit_env0             , ue_module_graph    = ue_module_graph unit_env0+            , ue_uic      = ue_uic unit_env0             }       modifySession $ \h ->         -- hscSetFlags takes care of updating the logger as well.@@ -957,19 +957,17 @@      updateHomeUnit :: GhcMonad m => Logger -> UnitEnv -> HomeUnitGraph -> (UnitId -> HomeUnitEnv -> m HomeUnitEnv)     updateHomeUnit logger unit_env updates = \uid homeUnitEnv -> do-      let cached_unit_dbs = homeUnitEnv_unit_dbs homeUnitEnv-          dflags = case HUG.unitEnv_lookup_maybe uid updates of+      let dflags = case HUG.unitEnv_lookup_maybe uid updates of             Nothing -> homeUnitEnv_dflags homeUnitEnv             Just env -> homeUnitEnv_dflags env           old_hpt = homeUnitEnv_hpt homeUnitEnv           home_units = HUG.allUnits (ue_home_unit_graph unit_env) -      (dbs,unit_state,home_unit,mconstants) <- liftIO $ initUnits logger dflags cached_unit_dbs home_units+      (unit_state,home_unit,mconstants) <- liftIO $ initUnits logger dflags (ue_uic unit_env) home_units        updated_dflags <- liftIO $ updatePlatformConstants dflags mconstants       pure HomeUnitEnv         { homeUnitEnv_units = unit_state-        , homeUnitEnv_unit_dbs = Just dbs         , homeUnitEnv_dflags = updated_dflags         , homeUnitEnv_hpt = old_hpt         , homeUnitEnv_home_unit = Just home_unit
GHC/Builtin/Names.hs view
@@ -1997,8 +1997,8 @@ anyTyConKey :: Unique anyTyConKey = mkPreludeTyConUnique 171 -zonkAnyTyConKey :: Unique-zonkAnyTyConKey = mkPreludeTyConUnique 172+unusedTypeTyConKey :: Unique+unusedTypeTyConKey = mkPreludeTyConUnique 172  -- Custom user type-errors errorMessageTypeErrorFamKey :: Unique
GHC/Builtin/PrimOps.hs view
@@ -18,7 +18,7 @@          primOpOutOfLine, primOpCodeSize,         primOpOkForSpeculation, primOpOkToDiscard,-        primOpIsWorkFree, primOpIsCheap, primOpFixity, primOpDocs, primOpDeprecations,+        primOpIsWorkFree, primOpIsCheap, primOpFixity, primOpDocs, PrimOpDoc(..), primOpDeprecations,         primOpIsDiv, primOpIsReallyInline,          PrimOpEffect(..), primOpEffect,@@ -165,7 +165,13 @@ See Note [GHC.Prim Docs] in GHC.Builtin.Utils -} -primOpDocs :: [(FastString, String)]+data PrimOpDoc+  = -- | Section header with title and description+    PrimOpSection String String+  | -- | Documentation for a named declaration+    PrimOpDecl FastString String++primOpDocs :: [PrimOpDoc] #include "primop-docs.hs-incl"  primOpDeprecations :: [(OccName, FastString)]
GHC/Builtin/Types.hs view
@@ -93,7 +93,7 @@         cTupleSelId, cTupleSelIdName,          -- * Any-        anyTyCon, anyTy, anyTypeOfKind, zonkAnyTyCon,+        anyTyCon, anyTy, anyTypeOfKind, unusedTypeTyCon,          -- * Recovery TyCon         makeRecoveryTyCon,@@ -298,7 +298,7 @@  wiredInTyCons = map (dataConTyCon . snd) boxingDataCons              ++ [ anyTyCon-                , zonkAnyTyCon+                , unusedTypeTyCon                 , boolTyCon                 , charTyCon                 , stringTyCon@@ -408,59 +408,90 @@ -- Any  {--Note [Any types]-~~~~~~~~~~~~~~~~-The type constructors `Any` and `ZonkAny` are closed type families declared thus:+Note [The types Any and UnusedType]+~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~+The type constructors `Any` and `UnusedType` are closed type families declared as: -    type family Any     :: forall k.        k where { }-    type family ZonkAny :: forall k. Nat -> k where { }+    type family Any        :: forall k.           k where { }+    type family UnusedType :: forall k. Symbol -> k where { }  They are used when we want a type of a particular kind, but we don't really care-what that type is.  The leading example is this: `ZonkAny` is used to instantiate-un-constrained type variables after type checking. For example, consider the-term (length [] :: Int), where--  length :: forall a. [a] -> Int-  []     :: forall a. [a]+what that type is. The leading example that is relevant for GHC itself is this: -We must type-apply `length` and `[]`, but to what type? It doesn't matter!-The typechecker will end up with+    `UnusedType` is used to instantiate unconstrained type variables after type+    checking. For example, consider the term (length [] :: Int), where -  length @alpha ([] @alpha)+      length :: forall a. [a] -> Int+      []     :: forall a. [a] -where `alpha` is an un-constrained unification variable.  The "zonking" process zaps-that unconstrained `alpha` to an arbitrary type (ZonkAny @Type 3), where the `3` is-arbitrary (see wrinkle (Any5) below).  This is done in `GHC.Tc.Zonk.Type.commitFlexi`.-So we end up with+    We must type-apply `length` and `[]`, but to what type? It doesn't matter!+    The typechecker will end up with -  length @(ZonkAny @Type 3) ([] @(ZonkAny @Type 3))+      length @alpha ([] @alpha) -`Any` and `ZonkAny` differ only in the presence of the `Nat` argument; see-wrinkle (Any4).+    where `alpha` is an unconstrained unification variable.  The "zonking" process+    zaps that unconstrained `alpha` to an arbitrary type (UnusedType @Type "a_3"),+    where the `3` is arbitrary (see wrinkle (Any3) below) and "a" is the name string+    of the meta variable. This is done in `GHC.Tc.Zonk.Type.commitFlexi`.+    So we end up with -Wrinkles:+      length @(UnusedType @Type "a_3") ([] @(UnusedType @Type "a_3")) -(Any1) `Any` and `ZonkAny` are kind polymorphic since in some program we may-   need to use `ZonkAny` to fill in a type variable of some kind other than *-   (see #959 for examples).+`Any` and `UnusedType` differ only in the presence of the `Symbol` argument; see (Any6). -(Any2) They are /closed/ type families, with no instances.  For example, suppose that+(Any1) They are /closed/ type families, with no instances.  For example, suppose that    with  alpha :: '(k1, k2)  we add a given coercion              g :: alpha ~ (Fst alpha, Snd alpha)-   and we zonked alpha = ZonkAny @(k1,k2) n.  Then, if `ZonkAny` was a /data/ type,-   we'd get inconsistency because we'd have a Given equality with `ZonkAny` on one+   and we zonked alpha = UnusedType @(k1,k2) n.  Then, if `UnusedType` was a /data/ type,+   we'd get inconsistency because we'd have a Given equality with `UnusedType` on one    side and '(,) on the other. See also #9097 and #9636. -   See #25244 for a suggestion that we instead use an /open/ type family for which-   you cannot provide instances.  Probably the difference is not very important.+   They are not /data/ types, and that's important for the code generator,+   because the code gen may enter a data value. -(Any3) They do not claim to be /data/ types, and that's important for-   the code generator, because the code gen may /enter/ a data value-   but never enters a function value.+   A closed type family with no equations behaves differently than an open type+   family with no equations due to Note [Insoluble fundeps] IFD0 in+   GHC.Tc.Solver.FunDeps, so it was argued in #25244 that perhaps 'Any' should+   rather be an open type family for which new equations cannot be written. -(Any4) `ZonkAny` takes a `Nat` argument so that we can readily make up /distinct/-   types (#24817).  Consider+(Any2) `Any` and `UnusedType` are kind polymorphic since in some programs we may+   need to use `UnusedType` to fill in a type variable of some kind other than Type+   e.g. TYPE r for some r, or types of the form _ -> Type. +(Any3) `Any` and `UnusedType` are wired-in so we can easily refer to them where we+    don't have a name environment.++(Any4) User facing aspects of the types Any and UnusedType:++   `Any` is defined in ghc-internal:GHC.Internal.Types, and exported. `Any`+    is available to users because it is a useful type in userspace and is thus+    re-exported from base:GHC.Exts.++    `UnusedType` is exported mainly for documentation in case a user stumbles over+    it in debug output of GHC.++    The key property of 'Any' is that it is safe to coerce a type to 'Any' as long+    as the representation is unchanged. That is, it is OK to use 'unsafeCoerce#' to+    go from 'ty :: TYPE r' to 'Any :: TYPE r' and back.+    This can be useful when e.g. implementing dependent maps or similar typed+    container types, storing values of type `Any`.++(Any5) Warnings about unused bindings of type `Any` and `UnusedType` are suppressed,+    following the same rationale of supressing warning about the unit type.++    For example, consider (#25895):++      do { forever (return ()); blah }++    where forever :: forall a b. IO a -> IO b+    Nothing constrains `b`, so it will be instantiated with `Any` or `UnusedType`.+    But we certainly don't want to complain about a discarded do-binding.++(Any6) Wrinkle - Pattern match checking.++   The first reason why `UnusedType` takes a `Symbol` argument is that+   we can readily make up /distinct/ types (#24817) for the Pmc.  Consider+      data SBool a where { STrue :: SBool True; SFalse :: SBool False }       foo :: forall a b. (SBool a, SBool b)@@ -473,53 +504,33 @@    Now, what are `alpha` and `beta`? If we zonk both of them to the same type    `Any @Type`, the pattern-match checker will (wrongly) report that the first    branch is inaccessible.  So we zonk them to two /different/ types:-       alpha :=  ZonkAny @Type 4   and   beta :=  ZonkAny @Type k 5+       alpha :=  UnusedType @Type "a_4"  and   beta :=  UnusedType @Type k "b_5"    (The actual numbers are arbitrary; they just need to differ.)     The unique-name generation comes from field `tcg_zany_n` of `TcGblEnv`; and-   `GHC.Tc.Zonk.Type.commitFlexi` calls `GHC.Tc.Utils.Monad.newZonkAnyType` to+   `GHC.Tc.Zonk.Type.commitFlexi` calls `GHC.Tc.Utils.Monad.newUnusedTypeType` to    make up a fresh type.     If this example seems unconvincing (e.g. in this case foo must be bottom)    see #24817 for larger but more compelling examples. -(Any5) `Any` and `ZonkAny` are wired-in so we can easily refer to it where we-    don't have a name environment (e.g. see Rules.matchRule for one example)--(Any6) `Any` is defined in library module ghc-prim:GHC.Types, and exported so that-    it is available to users.  For this reason it's treated like any other-    wired-in type:-      - has a fixed unique, anyTyConKey,-      - lives in the global name cache-    Currently `ZonkAny` is not available to users; but it could easily be.--(Any7) Properties of `Any`:-  * When `Any` is instantiated at a lifted type it is inhabited by at least one value,-    namely bottom.--  * You can safely coerce any /lifted/ type to `Any` and back with `unsafeCoerce`.--  * You can safely coerce any /unlifted/ type to `Any` and back with `unsafeCoerceUnlifted`.--  * You can coerce /any/ type to `Any` and back with `unsafeCoerce#`, but it's only safe when-    the kinds of both the type and `Any` match.--  * For lifted/unlifted types `unsafeCoerce[Unlifted]` should be preferred over-    `unsafeCoerce#` as they prevent accidentally coercing between types with kinds-    that don't match.+(Any7) Wrinkle - Error reporting. -    See examples in ghc-prim:GHC.Types+   There's a second reason why `UnusedType` takes a `Symbol` argument, which is that+   we use it to neatly display zonked unfilled metavariables without leaking+   implementation details of code generation. -(Any8) Warning about unused bindings of type `Any` and `ZonkAny` are suppressed,-    following the same rationale of supressing warning about the unit type.+   `UnusedType` is handled specially in the pretty-printer to avoid confusing+   compiler output. For example, `UnusedType "foo_3" :: Type` is displayed as `foo_3`. -    For example, consider (#25895):+   That special handling is implemented in GHC.Iface.Type.pprTyTcApp and more+   specifically ppr_iface_unused_ty_tycon. -     do { forever (return ()); blah }+   See testcase T27390 for an example of the pretty-printing in action. -    where forever :: forall a b. IO a -> IO b-    Nothing constrains `b`, so it will be instantiates with `Any` or `ZonkAny`.-    But we certainly don't want to complain about a discarded do-binding.+   Historical note: in the past, `UnusedType` was called `ZonkAny` (or `Any` before that).+   We renamed it to `UnusedType` and added this special treatment in the pretty-printer to avoid+   confusing mentions of zonking.  The Any tycon used to be quite magic, but we have since been able to implement it merely with an empty kind polymorphic type family. See #10886 for a@@ -532,7 +543,7 @@     mkWiredInTyConName UserSyntax gHC_TYPES (fsLit "Any") anyTyConKey anyTyCon  anyTyCon :: TyCon--- See Note [Any types]+-- See Note [The types Any and UnusedType] anyTyCon = mkFamilyTyCon anyTyConName binders res_kind Nothing                          (ClosedSynFamilyTyCon Nothing)                          Nothing@@ -547,23 +558,23 @@ anyTypeOfKind :: Kind -> Type anyTypeOfKind kind = mkTyConApp anyTyCon [kind] -zonkAnyTyConName :: Name-zonkAnyTyConName =-    mkWiredInTyConName UserSyntax gHC_TYPES (fsLit "ZonkAny") zonkAnyTyConKey zonkAnyTyCon+unusedTypeTyConName :: Name+unusedTypeTyConName =+    mkWiredInTyConName UserSyntax gHC_TYPES (fsLit "UnusedType") unusedTypeTyConKey unusedTypeTyCon -zonkAnyTyCon :: TyCon--- ZonkAnyTyCon :: forall k. Nat -> k--- See Note [Any types]-zonkAnyTyCon = mkFamilyTyCon zonkAnyTyConName-                         [ mkNamedTyConBinder Specified kv-                         , mkAnonTyConBinder nat_kv ]-                         (mkTyVarTy kv)+unusedTypeTyCon :: TyCon+-- unusedTypeTyCon :: forall k. Symbol -> k+-- See Note [The types Any and UnusedType]+unusedTypeTyCon = mkFamilyTyCon unusedTypeTyConName bndrs res_kind                          Nothing                          (ClosedSynFamilyTyCon Nothing)                          Nothing                          NotInjective   where-    [kv,nat_kv] = mkTemplateKindVars [liftedTypeKind, naturalTy]+    [kv,sym_kv] = mkTemplateKindVars [liftedTypeKind, typeSymbolKind]+    bndrs = [ mkNamedTyConBinder Specified kv+            , mkAnonTyConBinder sym_kv ]+    res_kind = mkTyVarTy kv  -- | Make a fake, recovery 'TyCon' from an existing one. -- Used when recovering from errors in type declarations
GHC/Builtin/Utils.hs view
@@ -245,13 +245,40 @@    | tc <- exposedPrimTyCons, let n = tyConName tc ]  ghcPrimDeclDocs :: Docs-ghcPrimDeclDocs = emptyDocs { docs_decls = listToUniqMap $ mapMaybe findName primOpDocs }+ghcPrimDeclDocs = emptyDocs+  { docs_decls = listToUniqMap $ mapMaybe declDoc primOpDocs+  , docs_structure = buildStructure primOpDocs+  }   where-    findName (nameStr, doc)-      | Just name <- lookupFsEnv ghcPrimNames nameStr-      = Just (name, [WithHsDocIdentifiers (mkGeneratedHsDocString doc) []])-      | otherwise = Nothing+    declDoc (PrimOpDecl fs doc)+      | not (null doc)+      , Just name <- lookupFsEnv ghcPrimNames fs+      = Just (name, [mkHsDoc doc])+    declDoc _ = Nothing +    buildStructure [] = []+    buildStructure (PrimOpSection title desc : rest) =+        DsiSectionHeading 1 (mkHsDoc title)+      : [DsiDocChunk (mkHsDoc desc) | not (null desc)]+     ++ buildStructure rest+    buildStructure items =+      let (decls, rest) = span isDecl items+          avails = mapMaybe declAvail decls+      in  [DsiExports (DefinitelyDeterministicAvails avails) | not (null avails)]+       ++ buildStructure rest++    isDecl (PrimOpDecl {}) = True+    isDecl _               = False++    declAvail (PrimOpDecl fs _)+      | Just name <- lookupFsEnv ghcPrimNames fs+      = Just $ if isTyConName name+               then AvailTC name [name]+               else Avail name+    declAvail _ = Nothing++    mkHsDoc s = WithHsDocIdentifiers (mkGeneratedHsDocString s) []+ ghcPrimNames :: FastStringEnv Name ghcPrimNames   = mkFsEnv@@ -286,18 +313,13 @@ {- Note [GHC.Prim Docs] ~~~~~~~~~~~~~~~~~~~~-For haddocks of GHC.Prim we generate a dummy haskell file (gen_hs_source) that-contains the type signatures and the comments (but no implementations)-specifically for consumption by haddock.--GHCi's :doc command reads directly from ModIface's though, and GHC.Prim has a-wired-in iface that has nothing to do with the above haskell file. The code-below converts primops.txt into an intermediate form that would later be turned-into a proper DeclDocMap.+GHCi's :doc command and Haddock read from ModIface's. GHC.Prim has a wired-in+iface whose docs are populated from primops.txt. -We output the docs as a list of pairs (name, docs). We use stringy names here-because mapping names to "Name"s is difficult for things like primtypes and-pseudoops.+genprimopcode --wired-in-docs generates the primOpDocs list (included as+primop-docs.hs-incl), which contains section headers (PrimOpSection) and+per-declaration documentation (PrimOpDecl). We use stringy names because+mapping names to "Name"s is difficult for things like primtypes and pseudoops.  Note [GHC.Prim Deprecations] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
GHC/Builtin/primops.txt.pp view
@@ -46,7 +46,7 @@ -- * The primitives are listed in this file, primops.txt.pp. --   It goes through CPP, which creates primops.txt. --   It is then consumed by the utility program genprimopcode, which produces---   the following three types of files.+--   the following types of files. -- --   1. The files with extension .hs-incl. --      They can be found by grepping for hs-incl.@@ -71,12 +71,7 @@ --      Additionally, we pattern match on PrimOp when generating Cmm in --      GHC/StgToCmm/Prim.hs. -----   2. The dummy Prim.hs file, which is used for Haddock and---      contains descriptions taken from primops.txt.pp.---      All definitions are replaced by placeholders.---      See Note [GHC.Prim Docs] in GHC.Builtin.Utils.------   3. The module PrimopWrappers.hs, which wraps every call for GHCi;+--   2. The module PrimopWrappers.hs, which wraps every call for GHCi; --      see Note [Primop wrappers] in GHC.Builtin.Primops for details. -- -- * This file does not list internal-only equality types
GHC/ByteCode/Asm.hs view
@@ -973,22 +973,27 @@ return_non_tuple V64 = error "return_non_tuple: vector"  {--  we can only handle up to a fixed number of words on the stack,-  because we need a stg_ctoi_tN stack frame for each size N. See-  Note [unboxed tuple bytecodes and tuple_BCO].+  The maximum number of words that can be spilled on the stack for+  a tuple return. This is limited by the encoding of the stack+  spill size in the call_info word (used by stg_ret_t): -  If needed, you can support larger tuples by adding more in-  Jumps.cmm, StgMiscClosures.cmm, Interpreter.c and MiscClosures.h and-  raising this limit.+    - On 32-bit platforms: 8-bit  (bits 24-31), max 255+    - On 64-bit platforms: 40-bit (bits 24-63) +  The stg_ctoi_t frame itself has no size limit since it reads the+  spill count from the TSO's ctoi_tuple_spill_words field. See+  Note [GHCi unboxed tuples stack spills] in StgMiscClosures.cmm.+   Note that the limit is the number of words passed on the stack.   If the calling convention passes part of the tuple in registers, the   maximum number of tuple elements may be larger. Elements can also   take multiple words on the stack (for example Double# on a 32 bit   platform).  -}-maxTupleReturnNativeStackSize :: WordOff-maxTupleReturnNativeStackSize = 62+maxTupleReturnNativeStackSize :: Platform -> WordOff+maxTupleReturnNativeStackSize platform = case platformWordSize platform of+  PW4 -> 255+  PW8 -> 1099511627775  {-   Construct the call_info word that stg_ctoi_t, stg_ret_t and stg_primcall@@ -997,9 +1002,10 @@    See Note [GHCi and native call registers] for more information.  -}-mkNativeCallInfoSig :: Platform -> NativeCallInfo -> Word32+mkNativeCallInfoSig :: Platform -> NativeCallInfo -> Word64 mkNativeCallInfoSig platform NativeCallInfo{..}-  | nativeCallType == NativeTupleReturn && nativeCallStackSpillSize > maxTupleReturnNativeStackSize+  | nativeCallType == NativeTupleReturn+  && nativeCallStackSpillSize > maxTupleReturnNativeStackSize platform   = pprPanic "mkNativeCallInfoSig: tuple too big for the bytecode compiler"              (ppr nativeCallStackSpillSize <+> text "stack words." <+>               text "Use -fobject-code to get around this limit"@@ -1008,8 +1014,9 @@   = -- 24 bits for register bitmap     assertPpr (length argRegs <= 24) (text "too many registers for bitmap:" <+> ppr (length argRegs)) -    -- 8 bits for continuation offset (only for NativeTupleReturn)-    assertPpr (cont_offset < 255) (text "continuation offset too large:" <+> ppr cont_offset)+    -- continuation offset must fit in available bits above the bitmap+    assertPpr (cont_offset <= fromIntegral (maxTupleReturnNativeStackSize platform))+              (text "continuation offset too large:" <+> ppr cont_offset)      -- all regs accounted for     assertPpr (all (`elem` (map fst argRegs)) (regSetToList nativeCallRegs))@@ -1023,12 +1030,12 @@      foldl' reg_bit 0 argRegs .|. (cont_offset `shiftL` 24)   where-    cont_offset :: Word32+    cont_offset :: Word64     cont_offset       | nativeCallType == NativeTupleReturn = fromIntegral nativeCallStackSpillSize       | otherwise                           = 0 -- there is no continuation for primcalls -    reg_bit :: Word32 -> (GlobalReg, Int) -> Word32+    reg_bit :: Word64 -> (GlobalReg, Int) -> Word64     reg_bit x (r, n)       | r `elemRegSet` nativeCallRegs = x .|. 1 `shiftL` n       | otherwise                     = x
GHC/ByteCode/Breakpoints.hs view
@@ -40,7 +40,7 @@ import Data.IntMap.Strict (IntMap) import qualified Data.IntMap.Strict as IM -import GHC.HsToCore.Breakpoints+import GHC.HsToCore.Breakpoints.Types import GHC.Iface.Syntax  import GHC.Unit.Module (Module)
GHC/ByteCode/Instr.hs view
@@ -490,11 +490,12 @@ bciStackUse (PUSH_ALTS bco _)     = 2 {- profiling only, restore CCCS -} +                                     3 + protoBCOStackUse bco bciStackUse (PUSH_ALTS_TUPLE bco info _) =-   -- (tuple_bco, call_info word, cont_bco, stg_ctoi_t)-   -- tuple-   -- (call_info, tuple_bco, stg_ret_t)+   -- ctoi frame: small (4 words) or generic (5 words, with old_spill)+   -- + tuple data + ret_t frame (3 words)    1 {- profiling only -} +-   7 + fromIntegral (nativeCallSize info) + protoBCOStackUse bco+   ctoi_frame + 3 + fromIntegral (nativeCallSize info) + protoBCOStackUse bco+   where ctoi_frame | nativeCallStackSpillSize info <= mAX_SMALL_TUPLE_CTOI = 4+                    | otherwise                                             = 5 bciStackUse (PUSH_PAD8)           = 1  -- overapproximation bciStackUse (PUSH_PAD16)          = 1  -- overapproximation bciStackUse (PUSH_PAD32)          = 1  -- overapproximation on 64bit arch
GHC/ByteCode/Linker.hs view
@@ -46,6 +46,7 @@ import GHC.Types.Unique.DFM  -- Standard libraries+import Control.Concurrent import Data.Array.Unboxed import Foreign.Ptr import GHC.Exts@@ -92,9 +93,12 @@   BCONPtrStr bs -> do     RemotePtr p <- fmap head $ interpCmd interp $ MallocStrings [bs]     pure $ fromIntegral p-  BCONPtrFS fs -> do-    RemotePtr p <- fmap head $ interpCmd interp $ MallocStrings [bytesFS fs]-    pure $ fromIntegral p+  BCONPtrFS fs -> modifyMVar (interpStringCache interp) $ \fs_env ->+    case lookupFsEnv fs_env fs of+      Just (RemotePtr p) -> pure (fs_env, fromIntegral p)+      Nothing -> do+        rp@(RemotePtr p) <- fmap head $ interpCmd interp $ MallocStrings [bytesFS fs]+        pure (extendFsEnv fs_env fs rp, fromIntegral p)   BCONPtrFFIInfo (FFIInfo {..}) -> do     RemotePtr p <- interpCmd interp $ PrepFFI ffiInfoArgs ffiInfoRet     pure $ fromIntegral p
GHC/ByteCode/Types.hs view
@@ -8,6 +8,8 @@ --  (c) The University of Glasgow 2002-2006 -- +#include "Bytecodes.h"+ -- | Bytecode assembler types module GHC.ByteCode.Types   ( CompiledByteCode(..), seqCompiledByteCode@@ -15,6 +17,7 @@   , FFIInfo(..)   , RegBitmap(..)   , NativeCallType(..), NativeCallInfo(..), voidTupleReturnInfo, voidPrimCallInfo+  , mAX_SMALL_TUPLE_CTOI   , ByteOff(..), WordOff(..), HalfWord(..)   , UnlinkedBCO(..), BCOPtr(..), BCONPtr(..)   , ItblEnv, ItblPtr(..)@@ -39,7 +42,7 @@ import GHC.Utils.Outputable import GHC.Builtin.PrimOps import GHC.Types.SptEntry-import GHC.HsToCore.Breakpoints+import GHC.HsToCore.Breakpoints.Types import GHC.ByteCode.Breakpoints import GHCi.Message import GHCi.RemoteTypes@@ -161,6 +164,12 @@ voidPrimCallInfo :: NativeCallInfo voidPrimCallInfo = NativeCallInfo NativePrimCall 0 emptyRegSet 0 +-- | Maximum nativeCallStackSpillSize for which we use a small+-- stg_ctoi_tN frame (no old_spill slot, no TSO access) instead of+-- the generic stg_ctoi_t frame.+mAX_SMALL_TUPLE_CTOI :: WordOff+mAX_SMALL_TUPLE_CTOI = MAX_SMALL_TUPLE_CTOI+ type ItblEnv = NameEnv (Name, ItblPtr) type AddrEnv = NameEnv (Name, AddrPtr)         -- We need the Name in the range so we know which@@ -296,4 +305,3 @@       = sep [text "BCO", ppr nm, text "with",              ppr (sizeFlatBag lits), text "lits",              ppr (sizeFlatBag ptrs), text "ptrs" ]-
GHC/Cmm.hs view
@@ -288,8 +288,8 @@   deriving (Eq)  -- | Should a data in this section be considered constant at runtime-sectionProtection :: Section -> SectionProtection-sectionProtection (Section t _) = case t of+sectionProtection :: SectionType -> SectionProtection+sectionProtection t = case t of     Text                    -> ReadOnlySection     ReadOnlyData            -> ReadOnlySection     RelocatableReadOnlyData -> WriteProtectedSection
GHC/Cmm/CommonBlockElim.hs view
@@ -26,6 +26,7 @@ import GHC.Types.Unique.FM import GHC.Types.Unique import GHC.Utils.Word64 (truncateWord64ToWord32)+import GHC.Utils.Panic.Plain (assert) import Control.Arrow (first, second) import Data.List.NonEmpty (NonEmpty (..)) import qualified Data.List.NonEmpty as NE@@ -74,6 +75,10 @@ -- (so avoid comparing them again) type DistinctBlocks = [CmmBlock] type Key = [Label]++-- | A substitution maps each eliminated block to its replacement.+--+-- Invariant: the substitution is idempotent, i.e. no value is a key. type Subst = LabelMap BlockId  -- The outer list groups by hash. We retain this grouping throughout.@@ -92,9 +97,24 @@           where             (new_subst2, db) = mergeBlockList subst dbs -    subst' = subst `mapUnion` new_substs+    subst' = extendSubst subst new_substs     updated_blocks = map (map (first (map (lookupBid subst')))) merged_blocks +-- | Extend the substitution with the merges of one more round.+--+-- A block that won a merge in an earlier round may have lost one in this+-- round, so the existing mapping is updated to keep the result idempotent:+--+-- > old:    A -> B+-- > new:    B -> C+-- > result: A -> C, B -> C+--+extendSubst :: Subst -> Subst -> Subst+extendSubst old new = assert (idempotent result) result+  where+    result = mapMap (lookupBid new) old `mapUnion` new+    idempotent s = not (any (`mapMember` s) s)+ -- Combine two lists of blocks. -- While they are internally distinct they can still share common blocks. mergeBlocks :: Subst -> DistinctBlocks -> DistinctBlocks -> (Subst, DistinctBlocks)@@ -200,9 +220,7 @@ eqBid :: LabelMap BlockId -> BlockId -> BlockId -> Bool eqBid subst bid bid' = lookupBid subst bid == lookupBid subst bid' lookupBid :: LabelMap BlockId -> BlockId -> BlockId-lookupBid subst bid = case mapLookup bid subst of-                        Just bid  -> lookupBid subst bid-                        Nothing -> bid+lookupBid subst bid = mapFindWithDefault bid bid subst  -- Middle nodes and expressions can contain BlockIds, in particular in -- CmmStackSlot and CmmBlock, so we have to use a special equality for
GHC/Cmm/Expr.hs view
@@ -435,6 +435,11 @@         CmmLit lit -> pprLit platform lit         _other     -> pprExpr1 platform e +-- | `op` usually, but `(op[width])` with -dppr-debug+withDebugWidth :: Width -> SDoc -> SDoc+withDebugWidth w doc =+  ifPprDebug (parens (doc <> brackets (ppr w))) doc+ -- Here's the precedence table from GHC.Cmm.Parser: -- %nonassoc '>=' '>' '<=' '<' '!=' '==' -- %left '|'@@ -457,15 +462,17 @@  infixMachOp1, infixMachOp7, infixMachOp8 :: MachOp -> Maybe SDoc -infixMachOp1 (MO_Eq     _) = Just (text "==")-infixMachOp1 (MO_Ne     _) = Just (text "!=")-infixMachOp1 (MO_Shl    _) = Just (text "<<")-infixMachOp1 (MO_U_Shr  _) = Just (text ">>")-infixMachOp1 (MO_U_Ge   _) = Just (text ">=")-infixMachOp1 (MO_U_Le   _) = Just (text "<=")-infixMachOp1 (MO_U_Gt   _) = Just (char '>')-infixMachOp1 (MO_U_Lt   _) = Just (char '<')-infixMachOp1 _             = Nothing+infixMachOp1 mop = case mop of+    (MO_Eq     w) -> Just $ withDebugWidth w (text "==")+    (MO_Ne     w) -> Just $ withDebugWidth w (text "!=")+    (MO_Shl    w) -> Just $ withDebugWidth w (text "<<")+    (MO_U_Shr  w) -> Just $ withDebugWidth w (text ">>")+    (MO_U_Ge   w) -> Just $ withDebugWidth w (text ">=")+    (MO_U_Le   w) -> Just $ withDebugWidth w (text "<=")+    (MO_U_Gt   w) -> Just $ withDebugWidth w (char '>')+    (MO_U_Lt   w) -> Just $ withDebugWidth w (char '<')+    _             -> Nothing+    where  -- %left '-' '+' pprExpr7 platform (CmmMachOp (MO_Add rep1) [x, CmmLit (CmmInt i rep2)]) | i < 0@@ -475,8 +482,8 @@    = pprExpr7 platform x <+> doc <+> pprExpr8 platform y pprExpr7 platform e = pprExpr8 platform e -infixMachOp7 (MO_Add _)  = Just (char '+')-infixMachOp7 (MO_Sub _)  = Just (char '-')+infixMachOp7 (MO_Add w)  = Just $ withDebugWidth w (char '+')+infixMachOp7 (MO_Sub w)  = Just $ withDebugWidth w (char '-') infixMachOp7 _           = Nothing  -- %left '/' '*' '%'@@ -485,9 +492,9 @@    = pprExpr8 platform x <+> doc <+> pprExpr9 platform y pprExpr8 platform e = pprExpr9 platform e -infixMachOp8 (MO_U_Quot _) = Just (char '/')-infixMachOp8 (MO_Mul _)    = Just (char '*')-infixMachOp8 (MO_U_Rem _)  = Just (char '%')+infixMachOp8 (MO_U_Quot w) = Just $ withDebugWidth w (char '/')+infixMachOp8 (MO_Mul w)    = Just $ withDebugWidth w (char '*')+infixMachOp8 (MO_U_Rem w)  = Just $ withDebugWidth w (char '%') infixMachOp8 _             = Nothing  pprExpr9 :: Platform -> CmmExpr -> SDoc@@ -537,11 +544,11 @@ infixMachOp :: MachOp -> Maybe SDoc infixMachOp mop         = case mop of-            MO_And    _ -> Just $ char '&'-            MO_Or     _ -> Just $ char '|'-            MO_Xor    _ -> Just $ char '^'-            MO_Not    _ -> Just $ char '~'-            MO_S_Neg  _ -> Just $ char '-' -- there is no unsigned neg :)+            MO_And    w -> Just $ withDebugWidth w $ char '&'+            MO_Or     w -> Just $ withDebugWidth w $ char '|'+            MO_Xor    w -> Just $ withDebugWidth w $ char '^'+            MO_Not    w -> Just $ withDebugWidth w $ char '~'+            MO_S_Neg  w -> Just $ withDebugWidth w $ char '-' -- there is no unsigned neg :)             _ -> Nothing  -- --------------------------------------------------------------------------
GHC/Cmm/InitFini.hs view
@@ -2,6 +2,7 @@ module GHC.Cmm.InitFini     ( InitOrFini(..)     , isInitOrFiniArray+    , isInitOrFiniSection     ) where  import GHC.Prelude@@ -63,8 +64,8 @@ data InitOrFini = IsInitArray | IsFiniArray  isInitOrFiniArray :: RawCmmDecl -> Maybe (InitOrFini, [CLabel])-isInitOrFiniArray (CmmData sect (CmmStaticsRaw _ lits))-  | Just initOrFini <- isInitOrFiniSection sect+isInitOrFiniArray (CmmData (Section t _) (CmmStaticsRaw _ lits))+  | Just initOrFini <- isInitOrFiniSection t   = Just (initOrFini, map get_label lits)   where     get_label :: CmmStatic -> CLabel@@ -72,7 +73,7 @@     get_label static = pprPanic "isInitOrFiniArray: invalid entry" (ppr static) isInitOrFiniArray _ = Nothing -isInitOrFiniSection :: Section -> Maybe InitOrFini-isInitOrFiniSection (Section InitArray _) = Just IsInitArray-isInitOrFiniSection (Section FiniArray _) = Just IsFiniArray+isInitOrFiniSection :: SectionType -> Maybe InitOrFini+isInitOrFiniSection InitArray = Just IsInitArray+isInitOrFiniSection FiniArray = Just IsFiniArray isInitOrFiniSection _                     = Nothing
GHC/Cmm/LayoutStack.hs view
@@ -408,6 +408,8 @@         where loc = getStackLoc area off stackmaps      CmmAssign (CmmLocal r) _other        -> sm { sm_regs = delFromUFM (sm_regs sm) r }+     CmmUnsafeForeignCall _ results _+       -> sm { sm_regs = delListFromUFM (sm_regs sm) results }      _other        -> sm 
GHC/Cmm/Lexer.hs view
@@ -1,7 +1,7 @@ {-# OPTIONS_GHC -fno-warn-unused-binds -fno-warn-missing-signatures #-} {-# LANGUAGE CPP #-} {-# LANGUAGE MagicHash #-}-{-# LINE 13 "_build/source-dist/ghc-9.14.1-src/ghc-9.14.1/compiler/GHC/Cmm/Lexer.x" #-}+{-# LINE 13 "_build/source-dist/ghc-9.14.2-src/ghc-9.14.2/compiler/GHC/Cmm/Lexer.x" #-} module GHC.Cmm.Lexer (    CmmToken(..), cmmlex,   ) where@@ -831,7 +831,7 @@         -- match when checking the right context, just         -- the first match will do. #endif-{-# LINE 144 "_build/source-dist/ghc-9.14.1-src/ghc-9.14.1/compiler/GHC/Cmm/Lexer.x" #-}+{-# LINE 144 "_build/source-dist/ghc-9.14.2-src/ghc-9.14.2/compiler/GHC/Cmm/Lexer.x" #-} data CmmToken   = CmmT_SpecChar  Char   | CmmT_DotDot
GHC/Cmm/Lint.hs view
@@ -91,8 +91,9 @@ -- byte/word mismatches.  lintCmmExpr :: CmmExpr -> CmmLint CmmType-lintCmmExpr (CmmLoad expr rep _alignment) = do-  _ <- lintCmmExpr expr+lintCmmExpr e@(CmmLoad expr rep _alignment) = do+  ty <- lintCmmExpr expr+  lintAddrTy e ty   -- Disabled, if we have the inlining phase before the lint phase,   -- we can have funny offsets due to pointer tagging. -- EZY   -- when (widthInBytes (typeWidth rep) >= platformWordSizeInBytes platform) $@@ -102,11 +103,11 @@   platform <- getPlatform   tys <- mapM lintCmmExpr args   lintShiftOp op (zip args tys)-  let machop_arg_widths = machOpArgReps platform op+  let machop_arg_widths_m = machOpArgReps platform op       arg_tys           = map (cmmExprType platform) args-  if map typeWidth arg_tys == machop_arg_widths+  if maybe False (\machop_arg_widths -> map typeWidth arg_tys == machop_arg_widths) machop_arg_widths_m     then cmmCheckMachOp op args tys-    else cmmLintMachOpErr expr arg_tys machop_arg_widths+    else cmmLintMachOpErr expr arg_tys machop_arg_widths_m lintCmmExpr (CmmRegOff reg offset)   = do let rep = typeWidth (cmmRegType reg)        lintCmmExpr (CmmMachOp (MO_Add rep)@@ -115,6 +116,15 @@   do platform <- getPlatform      return (cmmExprType platform expr) +-- We require every address value to be word-sized since we don't support 32+-- bit pointers on 64bit platforms.+lintAddrTy :: CmmExpr -> CmmType -> CmmLint ()+lintAddrTy e addr_ty = do+  p <- getPlatform+  -- We don't support any platforms where wordwidth /= ptrWidth currently.+  unless (addr_ty `cmmCompatType` bWord p) $ cmmLintErr (text "Non word-width address found in:" <+> pdoc p e)++ -- | Check for obviously out-of-bounds shift operations lintShiftOp :: MachOp -> [(CmmExpr, CmmType)] -> CmmLint () lintShiftOp op [(_, arg_ty), (CmmLit (CmmInt n _), _)]@@ -176,10 +186,10 @@             unless (erep `cmmCompatType` reg_ty) $               cmmLintAssignErr (CmmAssign reg expr) erep reg_ty -  CmmStore l r _alignment -> do-            _ <- lintCmmExpr l-            _ <- lintCmmExpr r-            return ()+  CmmStore addr rhs _alignment -> do+            addr_ty <- lintCmmExpr addr+            _ <- lintCmmExpr rhs+            lintAddrTy addr addr_ty    CmmUnsafeForeignCall target _formals actuals -> do             let lintArg expr = do@@ -282,8 +292,16 @@         Left err -> Left (hang info 2 err)         Right a  -> Right a -cmmLintMachOpErr :: CmmExpr -> [CmmType] -> [Width] -> CmmLint a-cmmLintMachOpErr expr argsRep opExpectsRep+cmmLintMachOpErr :: CmmExpr -> [CmmType] -> Maybe [Width] -> CmmLint a+cmmLintMachOpErr expr argsRep Nothing+     = do+       platform <- getPlatform+       cmmLintErr (text "in MachOp application: " $$+                   nest 2 (pdoc platform expr) $$+                      text "op is using unsupported width" $$+                      (text "arguments provide: " <+> ppr argsRep))++cmmLintMachOpErr expr argsRep (Just opExpectsRep)      = do        platform <- getPlatform        cmmLintErr (text "in MachOp application: " $$
GHC/Cmm/MachOp.hs view
@@ -144,8 +144,8 @@    -- Conversions.  Some of these will be NOPs.   -- Floating-point conversions use the signed variant.-  | MO_SF_Round    Width Width  -- Signed int -> Float-  | MO_FS_Truncate Width Width  -- Float -> Signed int+  | MO_SF_Round    Width Width  -- Signed int -> Float, but only W32/W64 inputs+  | MO_FS_Truncate Width Width  -- Float -> Signed int, only W32/W64 on the int side.   | MO_SS_Conv Width Width      -- Signed int -> Signed int   | MO_UU_Conv Width Width      -- unsigned int -> unsigned int   | MO_XX_Conv Width Width      -- int -> int; puts no requirements on the@@ -545,101 +545,110 @@ -- application of a MachOp is "type-correct" by checking that the MachReps of -- its arguments are the same as the MachOp expects.  This is used when -- linting a CmmExpr.+-- We also check if the given width is supported at all. But there might be+-- false positives. -machOpArgReps :: Platform -> MachOp -> [Width]+machOpArgReps :: Platform -> MachOp -> Maybe [Width] machOpArgReps platform op =   case op of-    MO_Add    w         -> [w,w]-    MO_Sub    w         -> [w,w]-    MO_Eq     w         -> [w,w]-    MO_Ne     w         -> [w,w]-    MO_Mul    w         -> [w,w]-    MO_S_MulMayOflo w   -> [w,w]-    MO_S_Quot w         -> [w,w]-    MO_S_Rem  w         -> [w,w]-    MO_S_Neg  w         -> [w]-    MO_U_Quot w         -> [w,w]-    MO_U_Rem  w         -> [w,w]+    MO_Add    w         -> Just [w,w]+    MO_Sub    w         -> Just [w,w]+    MO_Eq     w         -> Just [w,w]+    MO_Ne     w         -> Just [w,w]+    MO_Mul    w         -> Just [w,w]+    MO_S_MulMayOflo w   -> Just [w,w]+    MO_S_Quot w         -> Just [w,w]+    MO_S_Rem  w         -> Just [w,w]+    MO_S_Neg  w         -> Just [w]+    MO_U_Quot w         -> Just [w,w]+    MO_U_Rem  w         -> Just [w,w] -    MO_S_Ge w           -> [w,w]-    MO_S_Le w           -> [w,w]-    MO_S_Gt w           -> [w,w]-    MO_S_Lt w           -> [w,w]+    MO_S_Ge w           -> Just [w,w]+    MO_S_Le w           -> Just [w,w]+    MO_S_Gt w           -> Just [w,w]+    MO_S_Lt w           -> Just [w,w] -    MO_U_Ge w           -> [w,w]-    MO_U_Le w           -> [w,w]-    MO_U_Gt w           -> [w,w]-    MO_U_Lt w           -> [w,w]+    MO_U_Ge w           -> Just [w,w]+    MO_U_Le w           -> Just [w,w]+    MO_U_Gt w           -> Just [w,w]+    MO_U_Lt w           -> Just [w,w] -    MO_F_Add w          -> [w,w]-    MO_F_Sub w          -> [w,w]-    MO_F_Mul w          -> [w,w]-    MO_F_Quot w         -> [w,w]-    MO_F_Neg w          -> [w]-    MO_F_Min w          -> [w,w]-    MO_F_Max w          -> [w,w]+    MO_F_Add w          -> Just [w,w]+    MO_F_Sub w          -> Just [w,w]+    MO_F_Mul w          -> Just [w,w]+    MO_F_Quot w         -> Just [w,w]+    MO_F_Neg w          -> Just [w]+    MO_F_Min w          -> Just [w,w]+    MO_F_Max w          -> Just [w,w] -    MO_FMA _ l w        -> [vecwidth l w, vecwidth l w, vecwidth l w]+    MO_FMA _ l w        -> Just [vecwidth l w, vecwidth l w, vecwidth l w] -    MO_F_Eq  w          -> [w,w]-    MO_F_Ne  w          -> [w,w]-    MO_F_Ge  w          -> [w,w]-    MO_F_Le  w          -> [w,w]-    MO_F_Gt  w          -> [w,w]-    MO_F_Lt  w          -> [w,w]+    MO_F_Eq  w          -> Just [w,w]+    MO_F_Ne  w          -> Just [w,w]+    MO_F_Ge  w          -> Just [w,w]+    MO_F_Le  w          -> Just [w,w]+    MO_F_Gt  w          -> Just [w,w]+    MO_F_Lt  w          -> Just [w,w] -    MO_And   w          -> [w,w]-    MO_Or    w          -> [w,w]-    MO_Xor   w          -> [w,w]-    MO_Not   w          -> [w]-    MO_Shl   w          -> [w, wordWidth platform]-    MO_U_Shr w          -> [w, wordWidth platform]-    MO_S_Shr w          -> [w, wordWidth platform]+    MO_And   w          -> Just [w,w]+    MO_Or    w          -> Just [w,w]+    MO_Xor   w          -> Just [w,w]+    MO_Not   w          -> Just [w]+    MO_Shl   w          -> Just [w, wordWidth platform]+    MO_U_Shr w          -> Just [w, wordWidth platform]+    MO_S_Shr w          -> Just [w, wordWidth platform] -    MO_SS_Conv from _     -> [from]-    MO_UU_Conv from _     -> [from]-    MO_XX_Conv from _     -> [from]-    MO_SF_Round from _    -> [from]-    MO_FS_Truncate from _ -> [from]-    MO_FF_Conv from _     -> [from]-    MO_WF_Bitcast w       -> [w]-    MO_FW_Bitcast w       -> [w]+    MO_SS_Conv from _     -> Just [from]+    MO_UU_Conv from _     -> Just [from]+    MO_XX_Conv from _     -> Just [from]+    -- Only supports W32/W64+    MO_SF_Round from _w   -> onlyW32W64 from+    MO_FS_Truncate from to+      | to `notElem` [W32, W64] -> Nothing+      | otherwise -> onlyW32W64 from+    MO_FF_Conv from _     -> onlyW32W64 from+    MO_WF_Bitcast w       -> onlyW32W64 w+    MO_FW_Bitcast w       -> onlyW32W64 w -    MO_V_Shuffle  l w _ -> [vecwidth l w, vecwidth l w]-    MO_VF_Shuffle l w _ -> [vecwidth l w, vecwidth l w]+    MO_V_Shuffle  l w _ -> Just [vecwidth l w, vecwidth l w]+    MO_VF_Shuffle l w _ -> Just [vecwidth l w, vecwidth l w] -    MO_V_Broadcast _ w  -> [w]-    MO_V_Insert   l w   -> [vecwidth l w, w, W32]-    MO_V_Extract  l w   -> [vecwidth l w, W32]-    MO_VF_Broadcast _ w -> [w]-    MO_VF_Insert  l w   -> [vecwidth l w, w, W32]-    MO_VF_Extract l w   -> [vecwidth l w, W32]+    MO_V_Broadcast _ w  -> Just [w]+    MO_V_Insert   l w   -> Just [vecwidth l w, w, W32]+    MO_V_Extract  l w   -> Just [vecwidth l w, W32]+    MO_VF_Broadcast _ w -> Just [w]+    MO_VF_Insert  l w   -> Just [vecwidth l w, w, W32]+    MO_VF_Extract l w   -> Just [vecwidth l w, W32]       -- SIMD vector indices are always 32 bit -    MO_V_Add l w        -> [vecwidth l w, vecwidth l w]-    MO_V_Sub l w        -> [vecwidth l w, vecwidth l w]-    MO_V_Mul l w        -> [vecwidth l w, vecwidth l w]+    MO_V_Add l w        -> Just [vecwidth l w, vecwidth l w]+    MO_V_Sub l w        -> Just [vecwidth l w, vecwidth l w]+    MO_V_Mul l w        -> Just [vecwidth l w, vecwidth l w] -    MO_VS_Neg  l w      -> [vecwidth l w]-    MO_VS_Min  l w      -> [vecwidth l w, vecwidth l w]-    MO_VS_Max  l w      -> [vecwidth l w, vecwidth l w]+    MO_VS_Neg  l w      -> Just [vecwidth l w]+    MO_VS_Min  l w      -> Just [vecwidth l w, vecwidth l w]+    MO_VS_Max  l w      -> Just [vecwidth l w, vecwidth l w] -    MO_VU_Min  l w      -> [vecwidth l w, vecwidth l w]-    MO_VU_Max  l w      -> [vecwidth l w, vecwidth l w]+    MO_VU_Min  l w      -> Just [vecwidth l w, vecwidth l w]+    MO_VU_Max  l w      -> Just [vecwidth l w, vecwidth l w]      -- NOTE: The below is owing to the fact that floats use the SSE registers-    MO_VF_Add  l w      -> [vecwidth l w, vecwidth l w]-    MO_VF_Sub  l w      -> [vecwidth l w, vecwidth l w]-    MO_VF_Mul  l w      -> [vecwidth l w, vecwidth l w]-    MO_VF_Quot l w      -> [vecwidth l w, vecwidth l w]-    MO_VF_Neg  l w      -> [vecwidth l w]-    MO_VF_Min  l w      -> [vecwidth l w, vecwidth l w]-    MO_VF_Max  l w      -> [vecwidth l w, vecwidth l w]+    MO_VF_Add  l w      -> Just [vecwidth l w, vecwidth l w]+    MO_VF_Sub  l w      -> Just [vecwidth l w, vecwidth l w]+    MO_VF_Mul  l w      -> Just [vecwidth l w, vecwidth l w]+    MO_VF_Quot l w      -> Just [vecwidth l w, vecwidth l w]+    MO_VF_Neg  l w      -> Just [vecwidth l w]+    MO_VF_Min  l w      -> Just [vecwidth l w, vecwidth l w]+    MO_VF_Max  l w      -> Just [vecwidth l w, vecwidth l w] -    MO_RelaxedRead _    -> [wordWidth platform]-    MO_AlignmentCheck _ w -> [w]+    MO_RelaxedRead _    -> Just [wordWidth platform]+    MO_AlignmentCheck _ w -> Just [w]   where     vecwidth l w = widthFromBytes (l * widthInBytes w)+    onlyW32W64 w+      | w == W64 = Just [w]+      | w == W32 = Just [w]+      | otherwise = Nothing  ----------------------------------------------------------------------------- -- CallishMachOp
GHC/Cmm/Opt.hs view
@@ -290,9 +290,7 @@ -- the same comparison at the larger size.  cmmMachOpFoldM platform cmp [CmmMachOp conv [x], CmmLit (CmmInt i _)]-  |     -- powerPC NCG has a TODO for I8/I16 comparisons, so don't try-    platformArch platform `elem` [ArchX86, ArchX86_64],-        -- if the operand is widened:+  |     -- if the operand is widened:     Just (rep, signed, narrow_fn) <- maybe_conversion conv,         -- and this is a comparison operation:     Just narrow_cmp <- maybe_comparison cmp rep signed,@@ -395,26 +393,39 @@     one  = CmmLit (CmmInt 1 (wordWidth platform))  -- Now look for multiplication/division by powers of 2 (integers).--cmmMachOpFoldM platform mop [x, (CmmLit (CmmInt n _))]+--+-- Naively this is as simple a matter as left/right bit shifts,+-- but the Cmm representation if integral values quickly complicated the matter.+--+-- We must carefully narrow the value to be within the range of values for the+-- type's logical bit-width. However, Cmm only represents values as *signed*+-- integers internally yet the logical type may be unsigned. If we are dealing+-- with a negative integer type at width @_w@, the only negative number that+-- wraps around to be a positive power of 2 after calling narrowU is -2^(_w - 1)+-- which wraps round to 2^(_w - 1), and multiplying by -2^(_w - 1) is indeed+-- the same as a left shift by (w - 1), so this is OK.+--+-- ToDo: See #25664 (comment 605821) describing a change to the Cmm literal representation.+-- When/If this is completed, this code must be refactored to account for the explicit width sizes.+cmmMachOpFoldM platform mop [x, (CmmLit (CmmInt n _w))]   = case mop of         MO_Mul rep-           | Just p <- exactLog2 n ->+           | Just p <- exactLog2 (narrowU rep n) ->                  Just $! (cmmMachOpFold platform (MO_Shl rep) [x, CmmLit (CmmInt p $ wordWidth platform)])         MO_U_Quot rep-           | Just p <- exactLog2 n ->+           | Just p <- exactLog2 (narrowU rep n) ->                  Just $! (cmmMachOpFold platform (MO_U_Shr rep) [x, CmmLit (CmmInt p $ wordWidth platform)])         MO_U_Rem rep-           | Just _ <- exactLog2 n ->+           | Just _ <- exactLog2 (narrowU rep n)  ->                  Just $! (cmmMachOpFold platform (MO_And rep) [x, CmmLit (CmmInt (n - 1) rep)])         MO_S_Quot rep-           | Just p <- exactLog2 n,+           | Just p <- exactLog2 (narrowS rep n),              CmmReg _ <- x ->   -- We duplicate x in signedQuotRemHelper, hence require                                 -- it is a reg.  FIXME: remove this restriction.                 Just $! (cmmMachOpFold platform (MO_S_Shr rep)                   [signedQuotRemHelper rep p, CmmLit (CmmInt p $ wordWidth platform)])         MO_S_Rem rep-           | Just p <- exactLog2 n,+           | Just p <- exactLog2 (narrowS rep n),              CmmReg _ <- x ->   -- We duplicate x in signedQuotRemHelper, hence require                                 -- it is a reg.  FIXME: remove this restriction.                 -- We replace (x `rem` 2^p) by (x - (x `quot` 2^p) * 2^p).
GHC/Cmm/Parser.hs view
@@ -3095,9 +3095,10 @@     , allWidths "pext" MO_Pext     , allWidths "cmpxchg" MO_Cmpxchg     , allWidths "xchg" MO_Xchg-    , allWidths "load_relaxed" (\w -> MO_AtomicRead w MemOrderAcquire)+    , allWidths "load_relaxed" (\w -> MO_AtomicRead w MemOrderRelaxed)     , allWidths "load_acquire" (\w -> MO_AtomicRead w MemOrderAcquire)     , allWidths "load_seqcst" (\w -> MO_AtomicRead w MemOrderSeqCst)+    , allWidths "store_relaxed" (\w -> MO_AtomicWrite w MemOrderRelaxed)     , allWidths "store_release" (\w -> MO_AtomicWrite w MemOrderRelease)     , allWidths "store_seqcst" (\w -> MO_AtomicWrite w MemOrderSeqCst)     , allWidths "fetch_add" (\w -> MO_AtomicRMW w AMO_Add)
GHC/Cmm/Sink.hs view
@@ -26,77 +26,75 @@  import GHC.Exts (inline) --- -------------------------------------------------------------------------------- Sinking and inlining+--------------------------------------------------------------------------------+{- Note [Sinking and inlining]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+Sinking is an optimisation pass that+ (a) moves assignments closer to their uses, to reduce register pressure+ (b) pushes assignments into a single branch of a conditional if possible+ (c) inlines assignments to registers that are mentioned only once+ (d) discards dead assignments --- This is an optimisation pass that---  (a) moves assignments closer to their uses, to reduce register pressure---  (b) pushes assignments into a single branch of a conditional if possible---  (c) inlines assignments to registers that are mentioned only once---  (d) discards dead assignments------ This tightens up lots of register-heavy code.  It is particularly--- helpful in the Cmm generated by the Stg->Cmm code generator, in--- which every function starts with a copyIn sequence like:------    x1 = R1---    x2 = Sp[8]---    x3 = Sp[16]---    if (Sp - 32 < SpLim) then L1 else L2------ we really want to push the x1..x3 assignments into the L2 branch.------ Algorithm:------  * Start by doing liveness analysis.------  * Keep a list of assignments A; earlier ones may refer to later ones.---    Currently we only sink assignments to local registers, because we don't---    have liveness information about global registers.------  * Walk forwards through the graph, look at each node N:------    * If it is a dead assignment, i.e. assignment to a register that is---      not used after N, discard it.------    * Try to inline based on current list of assignments---      * If any assignments in A (1) occur only once in N, and (2) are---        not live after N, inline the assignment and remove it---        from A.------      * If an assignment in A is cheap (RHS is local register), then---        inline the assignment and keep it in A in case it is used afterwards.------      * Otherwise don't inline.------    * If N is assignment to a local register pick up the assignment---      and add it to A.------    * If N is not an assignment to a local register:---      * remove any assignments from A that conflict with N, and---        place them before N in the current block.  We call this---        "dropping" the assignments.------      * An assignment conflicts with N if it:---        - assigns to a register mentioned in N---        - mentions a register assigned by N---        - reads from memory written by N---      * do this recursively, dropping dependent assignments------    * At an exit node:---      * drop any assignments that are live on more than one successor---        and are not trivial---      * if any successor has more than one predecessor (a join-point),---        drop everything live in that successor. Since we only propagate---        assignments that are not dead at the successor, we will therefore---        eliminate all assignments dead at this point. Thus analysis of a---        join-point will always begin with an empty list of assignments.--------- As a result of above algorithm, sinking deletes some dead assignments--- (transitively, even).  This isn't as good as removeDeadAssignments,--- but it's much cheaper.+This tightens up lots of register-heavy code.  It is particularly+helpful in the Cmm generated by the Stg->Cmm code generator, in+which every function starts with a copyIn sequence like: +   x1 = R1+   x2 = Sp[8]+   x3 = Sp[16]+   if (Sp - 32 < SpLim) then L1 else L2++we really want to push the x1..x3 assignments into the L2 branch.++Algorithm:++ * Start by doing liveness analysis.++ * Keep a list of assignments A; earlier ones may refer to later ones.+   Currently we only sink assignments to local registers, because we don't+   have liveness information about global registers.++ * Walk forwards through the graph, look at each node N:++   * If it is a dead assignment, i.e. assignment to a register that is+     not used after N, discard it.++   * Try to inline based on current list of assignments+     * If any assignments in A (1) occur only once in N, and (2) are+       not live after N, inline the assignment and remove it+       from A.++     * If an assignment in A is cheap (RHS is local register), then+       inline the assignment and keep it in A in case it is used afterwards.++     * Otherwise don't inline.++   * If N is an assignment to a local register, pick up the assignment+     and add it to A.++   * If N is not an assignment to a local register:+     * remove any assignments from A that conflict with N, and+       place them before N in the current block.  We call this+       "dropping" the assignments.+       (See Note [When does an assignment conflict?] for what it means for+        A to conflict with N.)++     * do this recursively, dropping dependent assignments++   * At an exit node:+     * drop any assignments that are live on more than one successor+       and are not trivial+     * if any successor has more than one predecessor (a join-point),+       drop everything live in that successor. Since we only propagate+       assignments that are not dead at the successor, we will therefore+       eliminate all assignments dead at this point. Thus analysis of a+       join-point will always begin with an empty list of assignments.++As a result of above algorithm, sinking deletes some dead assignments+(transitively, even).  This isn't as good as removeDeadAssignments,+but it's much cheaper.+-}+ -- ----------------------------------------------------------------------------- -- things that we aren't optimising very well yet. --@@ -648,110 +646,171 @@  -- ----------------------------------------------------------------------------- +{- Note [When does an assignment conflict?]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+An assignment 'A' conflicts with a statement 'N' if any of the following+conditions are satisfied:++  (C1) 'A' assigns to a register mentioned in 'N'+  (C2) 'A' mentions a register assigned by 'N'+  (C3) 'A' reads from memory written by 'N'++In such a situation, it is not safe to commute 'A' past 'N'. For example,+it is not safe to commute++  A: r = 1+  N: s = r++because 'r' may be undefined or hold a different value before 'A'.++Remarks:++  (C3) includes all foreign calls, as they may modify the heap/stack.++  (C1) includes the following two situations:++    (C1a) 'N' defines the LHS register in the assignment 'A', for example:++      A: r = <expr>+      N: r = <other_expr>++    (C1b) 'N' defines a register used in the RHS of 'A', for example:++      A: r = s+      N: s = <expr>++    (C1c) 'suspendThread' clobbers every global register not backed by a+          real register, as noted in #19237.++Forgetting (C1a) led to bug #26550, in which we incorrectly commuted++  A: _c1rB::Fx2V128 = <0.0 :: W64, 0.0 :: W64>+  N: _c1rB::Fx2V128 = %MO_VF_Insert_2_W64(<0.0 :: W64,0.0 :: W64>,%MO_F_Add_W64(F64[R1 + 7], 3.0 :: W64),0 :: W32)++-}+ -- | @conflicts (r,e) node@ is @False@ if and only if the assignment -- @r = e@ can be safely commuted past statement @node@.+--+-- See Note [When does an assignment conflict?]. conflicts :: Platform -> Assignment -> CmmNode O x -> Bool-conflicts platform (r, rhs, addr) node+conflicts platform assig@(r, rhs, addr) node -  -- (1) node defines registers used by rhs of assignment. This catches-  -- assignments and all three kinds of calls. See Note [Sinking and calls]-  | globalRegistersConflict platform rhs node                       = True-  | localRegistersConflict  platform rhs node                       = True+  -- (C1) node defines registers that are either the assigned register or+  -- are used by the rhs of the assignment.+  -- This catches assignments and all three kinds of calls.+  -- See Note [Sinking and calls]+  | globalRegistersConflict platform rhs   node                     = True+  | localRegistersConflict  platform assig node                     = True -  -- (2) node uses register defined by assignment+  -- (C2) node uses register defined by assignment   | foldRegsUsed platform (\b r' -> r == r' || b) False node        = True -  -- (3) a store to an address conflicts with a read of the same memory+  -- (C3) Node writes to memory that is read by the assignment.++  -- (a) a store to an address conflicts with a read of the same memory   | CmmStore addr' e _ <- node   , memConflicts addr (loadAddr platform addr' (cmmExprWidth platform e)) = True -  -- (4) an assignment to Hp/Sp conflicts with a heap/stack read respectively-  | HeapMem    <- addr, CmmAssign (CmmGlobal (GlobalRegUse Hp _)) _ <- node        = True-  | StackMem   <- addr, CmmAssign (CmmGlobal (GlobalRegUse Sp _)) _ <- node        = True-  | SpMem{}    <- addr, CmmAssign (CmmGlobal (GlobalRegUse Sp _)) _ <- node        = True+  -- (b) an assignment to Hp/Sp conflicts with a heap/stack read respectively+  | CmmAssign (CmmGlobal (GlobalRegUse Hp _)) _ <- node+  , memConflicts addr HeapMem+  = True+  | CmmAssign (CmmGlobal (GlobalRegUse Sp _)) _ <- node+  , memConflicts addr StackMem+  = True -  -- (5) foreign calls clobber heap: see Note [Foreign calls clobber heap]+  -- (c) foreign calls clobber heap: see Note [Foreign calls clobber heap]   | CmmUnsafeForeignCall{} <- node, memConflicts addr AnyMem      = True -  -- (6) suspendThread clobbers every global register not backed by a real-  -- register. It also clobbers heap and stack but this is handled by (5)+  -- (d) native calls clobber any memory+  | CmmCall{} <- node, memConflicts addr AnyMem                   = True++  -- (C1c) suspendThread clobbers every global register not backed by a real+  -- register. (It also clobbers heap and stack, but this is handled by (C3)(c) above.)   | CmmUnsafeForeignCall (PrimTarget MO_SuspendThread) _ _ <- node   , foldRegsUsed platform (\b g -> globalRegMaybe platform g == Nothing || b) False rhs   = True -  -- (7) native calls clobber any memory-  | CmmCall{} <- node, memConflicts addr AnyMem                   = True--  -- (8) otherwise, no conflict   | otherwise = False  {- Note [Inlining foldRegsDefd]-   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~-   foldRegsDefd is, after optimization, *not* a small function so-   it's only marked INLINEABLE, but not INLINE.--   However in some specific cases we call it *very* often making it-   important to avoid the overhead of allocating the folding function.+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+foldRegsDefd is, after optimization, *not* a small function so+it's only marked INLINEABLE, but not INLINE. -   So we simply force inlining via the magic inline function.-   For T3294 this improves allocation with -O by ~1%.+However in some specific cases we call it *very* often making it+important to avoid the overhead of allocating the folding function. +So we simply force inlining via the magic inline function.+For T3294 this improves allocation with -O by ~1%. -} --- Returns True if node defines any global registers that are used in the--- Cmm expression+-- | Returns @True@ if @node@ defines any global registers that are used in the+-- Cmm expression.+--+-- See (C1) in Note [When does an assignment conflict?]. globalRegistersConflict :: Platform -> CmmExpr -> CmmNode e x -> Bool globalRegistersConflict platform expr node =    -- See Note [Inlining foldRegsDefd]    inline foldRegsDefd platform (\b r -> b || globalRegUsedIn platform (globalRegUse_reg r) expr)                 False node+    -- NB: no need to worry about (C1a), as the LHS of an assignment is always+    -- a local register, never a global register. --- Returns True if node defines any local registers that are used in the--- Cmm expression-localRegistersConflict :: Platform -> CmmExpr -> CmmNode e x -> Bool-localRegistersConflict platform expr node =+-- | Given an assignment @local_reg := expr@, return @True@ if @node@ defines any+-- local registers mentioned in the assignment.+--+-- See (C1) in Note [When does an assignment conflict?].+localRegistersConflict :: Platform -> Assignment -> CmmNode e x -> Bool+localRegistersConflict platform (r, expr, _) node =     -- See Note [Inlining foldRegsDefd]-    inline foldRegsDefd platform (\b r -> b || regUsedIn platform (CmmLocal  r) expr)-                 False node+    inline foldRegsDefd platform+      (\b r' ->+           b+        || r' == r -- (C1a)+        || regUsedIn platform (CmmLocal r') expr -- (C1b)+      )+      False node --- Note [Sinking and calls]--- ~~~~~~~~~~~~~~~~~~~~~~~~--- We have three kinds of calls: normal (CmmCall), safe foreign (CmmForeignCall)--- and unsafe foreign (CmmUnsafeForeignCall). We perform sinking pass after--- stack layout (see Note [Sinking after stack layout]) which leads to two--- invariants related to calls:------   a) during stack layout phase all safe foreign calls are turned into---      unsafe foreign calls (see Note [Lower safe foreign calls]). This---      means that we will never encounter CmmForeignCall node when running---      sinking after stack layout------   b) stack layout saves all variables live across a call on the stack---      just before making a call (remember we are not sinking assignments to---      stack):------       L1:---          x = R1---          P64[Sp - 16] = L2---          P64[Sp - 8]  = x---          Sp = Sp - 16---          call f() returns L2---       L2:------      We will attempt to sink { x = R1 } but we will detect conflict with---      { P64[Sp - 8]  = x } and hence we will drop { x = R1 } without even---      checking whether it conflicts with { call f() }. In this way we will---      never need to check any assignment conflicts with CmmCall. Remember---      that we still need to check for potential memory conflicts.------ So the result is that we only need to worry about CmmUnsafeForeignCall nodes--- when checking conflicts (see Note [Unsafe foreign calls clobber caller-save registers]).--- This assumption holds only when we do sinking after stack layout. If we run--- it before stack layout we need to check for possible conflicts with all three--- kinds of calls. Our `conflicts` function does that by using a generic--- foldRegsDefd and foldRegsUsed functions defined in DefinerOfRegs and--- UserOfRegs typeclasses.---+{- Note [Sinking and calls]+~~~~~~~~~~~~~~~~~~~~~~~~~~~+We have three kinds of calls: normal (CmmCall), safe foreign (CmmForeignCall)+and unsafe foreign (CmmUnsafeForeignCall). We perform sinking pass after+stack layout (see Note [Sinking after stack layout]) which leads to two+invariants related to calls:++  a) during stack layout phase all safe foreign calls are turned into+     unsafe foreign calls (see Note [Lower safe foreign calls]). This+     means that we will never encounter CmmForeignCall node when running+     sinking after stack layout++  b) stack layout saves all variables live across a call on the stack+     just before making a call (remember we are not sinking assignments to+     stack):++      L1:+         x = R1+         P64[Sp - 16] = L2+         P64[Sp - 8]  = x+         Sp = Sp - 16+         call f() returns L2+      L2:++     We will attempt to sink { x = R1 } but we will detect conflict with+     { P64[Sp - 8]  = x } and hence we will drop { x = R1 } without even+     checking whether it conflicts with { call f() }. In this way we will+     never need to check any assignment conflicts with CmmCall. Remember+     that we still need to check for potential memory conflicts.++So the result is that we only need to worry about CmmUnsafeForeignCall nodes+when checking conflicts (see Note [Unsafe foreign calls clobber caller-save registers]).+This assumption holds only when we do sinking after stack layout. If we run+it before stack layout we need to check for possible conflicts with all three+kinds of calls. Our `conflicts` function does that by using a generic+foldRegsDefd and foldRegsUsed functions defined in DefinerOfRegs and+UserOfRegs typeclasses.+-}  -- An abstraction of memory read or written. data AbsMem
GHC/CmmToAsm/AArch64/CodeGen.hs view
@@ -359,13 +359,10 @@ -- data Register         = Fixed Format Reg InstrBlock+        -- ^ It can be unsafe to clobber the result reg, as it might map to a+        -- local variable.         | Any   Format (Reg -> InstrBlock)---- | Sometimes we need to change the Format of a register. Primarily during--- conversion.-swizzleRegisterRep :: Format -> Register -> Register-swizzleRegisterRep format (Fixed _ reg code) = Fixed format reg code-swizzleRegisterRep format (Any _ codefn)     = Any   format codefn+        -- ^ A destination the caller decides, prevents redundant moves  -- | Grab the Reg for a CmmReg getRegisterReg :: Platform -> CmmReg -> Reg@@ -373,8 +370,9 @@ getRegisterReg _ (CmmLocal (LocalReg u pk))   = RegVirtual $ mkVirtualReg u (cmmTypeFormat pk) -getRegisterReg platform (CmmGlobal reg@(GlobalRegUse mid _))-  = case globalRegMaybe platform mid of+getRegisterReg platform (CmmGlobal reg@(GlobalRegUse mid ty))+  = assert (formatInBytes (cmmTypeFormat ty) >= 4) $+    case globalRegMaybe platform mid of         Just reg -> RegReal reg         Nothing  -> pprPanic "getRegisterReg-memory" (ppr $ CmmGlobal reg)         -- By this stage, the only MagicIds remaining should be the@@ -385,11 +383,19 @@ -- ----------------------------------------------------------------------------- -- General things for putting together code sequences --- | The dual to getAnyReg: compute an expression into a register, but---      we don't mind which one it is.+-- | Computes the `Register` value into a concrete register, but we can't pick which one.+-- This means the register might be mapped to a global or local variable and+-- we can only mutate the result reg in place if we know the Cmm expression can't+-- refer to local or global variables.+-- Subword results will be truncated as described by the subword invariant.+-- See Note [Subword operations on AArch64]. getSomeReg :: CmmExpr -> NatM (Reg, Format, InstrBlock) getSomeReg expr = do   r <- getRegister expr+  someReg r++someReg :: Register -> NatM (Reg, Format, InstrBlock)+someReg r =   case r of     Any rep code -> do         tmp <- getNewRegNat rep@@ -533,6 +539,8 @@ litToImm' :: CmmLit -> NatM (Operand, InstrBlock) litToImm' lit = return (OpImm (litToImm lit), nilOL) +-- | Return a computation/block of instructions that corresponds to the expressions+-- value. Values are already truncated if needed. See Note [Subword operations on AArch64]. getRegister :: CmmExpr -> NatM Register getRegister e = do   config <- getConfig@@ -547,20 +555,39 @@ opRegWidth W8  = W32  -- w opRegWidth w   = pprPanic "opRegWidth" (text "Unsupported width" <+> ppr w) --- Note [Signed arithmetic on AArch64]--- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--- Handling signed arithmetic on sub-word-size values on AArch64 is a bit--- tricky as Cmm's type system does not capture signedness. While 32-bit values--- are fairly easy to handle due to AArch64's 32-bit instruction variants--- (denoted by use of %wN registers), 16- and 8-bit values require quite some--- care.+-- Note [Subword operations on AArch64]+-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+-- Handling subword operations on AArch64 is a bit tricky. 32-bit values are fairly+-- easy to handle due to AArch64's 32-bit instruction variants. 16- and 8-bit+-- values require quite some care. The platform doesn't provide operations at+-- widths below 32bit. Which means we have to simulate them using wider operations.+-- Signed arithmetic on sub-word-size values on AArch64 is a bit tricky as Cmm's+-- type system does not capture signedness. If we have a 8 bit value the high+-- bits could be sign or zero extended with no easy way to tell. ----- We handle 16-and 8-bit values by using the 32-bit operations and+-- To work around this handle 16-and 8-bit values by using the 32-bit operations and -- sign-/zero-extending operands and truncate results as necessary. For -- simplicity we maintain the invariant that a register containing a -- sub-word-size value always contains the zero-extended form of that value -- in between operations. --+-- Concretely we establish this invariant on every input into the function for which+-- we generate code for in the NCG. This means:+-- * Global STG register access+-- * memory reads+-- * function arguments+-- * ffi results+-- * function call results+-- * results from any subexpression. (Including results produced by getRegister/getSomeReg)+--+-- This means we can assume the invariant when generated code for expression trees+-- or machops reading local variables, avoiding (some) redundant extensions. But+-- we have to take great care to uphold the invariant when computing new values.+--+-- We used to do the inverse. Re-establish the invariant for any operation that+-- is sensitive to values in the high bits. But that turned out to produce worse+-- code and wasn't any less likely to result in new bugs in practice.+-- -- For instance, consider the program, -- --    test(bits64 buffer)@@ -581,6 +608,9 @@ -- requires no extension and no truncate since we can assume that -- `c` is zero-extended. --+-- Down the line I think the right way to approach this is to operate more over+-- the `Register` type and store sign extension information inside it.+-- -- TODO: --   Don't use Width in Operands --   Instructions should rather carry a RegWidth@@ -768,20 +798,37 @@       getRegister (CmmLoad e (cmmBits w) NaturallyAligned)      CmmMachOp op [e] -> do-      (reg, _format, code) <- getSomeReg e+      register <- getRegister e+      (reg, _format, code) <- someReg register       case op of-        MO_Not w -> return $ Any (intFormat w) $ \dst ->+        -- XX Conversion+        -- truncateSubwordRegister: See Note [Subword operations on AArch64].+        MO_XX_Conv from to+          | to >= from -> pure $ swizzleRegisterRep register (intFormat to)+          | otherwise -> pure $ truncateSubwordRegister to register++        -- truncateSubwordRegister: See Note [Subword operations on AArch64].+        MO_Not w -> return $ truncateSubwordRegister w $ Any (intFormat w) $ \dst ->             let w' = opRegWidth w              in code `snocOL`-                MVN (OpReg w' dst) (OpReg w' reg) `appOL`-                truncateReg w' w dst -- See Note [Signed arithmetic on AArch64]+                MVN (OpReg w' dst) (OpReg w' reg) -        MO_S_Neg w -> negate code w reg-        MO_F_Neg w -> return $ Any (floatFormat w) (\dst -> code `snocOL` NEG (OpReg w dst) (OpReg w reg))+        -- truncateSubwordRegister: See Note [Subword operations on AArch64].+        MO_S_Neg w -> truncateSubwordRegister w <$> do+          let op_w = opRegWidth w+          (src, _fmt, reg_code) <- someReg $ signExtendRegister w op_w register+          pure $ Any (intFormat w) $ \dst -> reg_code `snocOL` (NEG (OpReg op_w dst) (OpReg op_w src)) -        MO_SF_Round    from to -> return $ Any (floatFormat to) (\dst -> code `snocOL` SCVTF (OpReg to dst) (OpReg from reg))  -- (Signed ConVerT Float)-        MO_FS_Truncate from to -> return $ Any (intFormat to) (\dst -> code `snocOL` FCVTZS (OpReg to dst) (OpReg from reg)) -- (float convert (-> zero) signed)+        MO_F_Neg w -> return $ Any fmt (\dst -> code `snocOL` NEG (OpReg w dst) (OpReg w reg))+          where fmt = floatFormat w +        MO_SF_Round    from to ->+          massert (from >= W32) >>+          return $ Any (floatFormat to) (\dst -> code `snocOL` SCVTF (OpReg to dst) (OpReg from reg))  -- (Signed ConVerT Float)+        MO_FS_Truncate from to ->+          massert (to >= W32) >>+          return $ Any (intFormat to) (\dst -> code `snocOL` FCVTZS (OpReg to dst) (OpReg from reg)) -- (float convert (-> zero) signed)+         -- TODO this is very hacky         -- Note, UBFM and SBFM expect source and target register to be of the same size, so we'll use @max from to@         -- UBFM will set the high bits to 0. SBFM will copy the sign (sign extend).@@ -791,8 +838,6 @@         MO_WF_Bitcast w    -> return $ Any (floatFormat w)  (\dst -> code `snocOL` FMOV (OpReg w dst) (OpReg w reg))         MO_FW_Bitcast w    -> return $ Any (intFormat w)    (\dst -> code `snocOL` FMOV (OpReg w dst) (OpReg w reg)) -        -- Conversions-        MO_XX_Conv _from to -> swizzleRegisterRep (intFormat to) <$> getRegister e          MO_Eq {} -> notUnary         MO_Ne {} -> notUnary@@ -871,25 +916,13 @@         toImm W256 = (OpImm (ImmInt 255))         toImm W512 = (OpImm (ImmInt 511)) -        -- In the case of 16- or 8-bit values we need to sign-extend to 32-bits-        -- See Note [Signed arithmetic on AArch64].-        negate code w reg = do-            let w' = opRegWidth w-            (reg', code_sx) <- signExtendReg w w' reg-            return $ Any (intFormat w) $ \dst ->-                code `appOL`-                code_sx `snocOL`-                NEG (OpReg w' dst) (OpReg w' reg') `appOL`-                truncateReg w' w dst-         ss_conv from to reg code =             let w' = opRegWidth (max from to)-            in return $ Any (intFormat to) $ \dst ->-                code `snocOL`-                SBFM (OpReg w' dst) (OpReg w' reg) (OpImm (ImmInt 0)) (toImm (min from to)) `appOL`-                -- At this point an 8- or 16-bit value would be sign-extended+            in return $ truncateSubwordRegister to $ Any (intFormat to) $ \dst ->+                  code `snocOL`+                  SBFM (OpReg w' dst) (OpReg w' reg) (OpImm (ImmInt 0)) (toImm (min from to))+                -- At this point an 8- or 16-bit value is sign-extended                 -- to 32-bits. Truncate back down the final width.-                truncateReg w' to dst      -- Dyadic machops:     --@@ -906,20 +939,21 @@     CmmMachOp (MO_Sub _) [expr'@(CmmReg (CmmGlobal _r)), CmmLit (CmmInt 0 _)] -> getRegister' config plat expr'     -- Immediates are handled via `getArithImm` in the generic code path. -    CmmMachOp (MO_U_Quot w) [x, y] | w == W8 -> do-      (reg_x, _format_x, code_x) <- getSomeReg x-      (reg_y, _format_y, code_y) <- getSomeReg y-      return $ Any (intFormat w) (\dst -> code_x `appOL` code_y `snocOL` annExpr expr (UXTB (OpReg w reg_x) (OpReg w reg_x)) `snocOL`-                                                                        (UXTB (OpReg w reg_y) (OpReg w reg_y)) `snocOL`-                                                                        (UDIV (OpReg w dst) (OpReg w reg_x) (OpReg w reg_y)))-    CmmMachOp (MO_U_Quot w) [x, y] | w == W16 -> do+    CmmMachOp (MO_U_Quot w) [x, y] | w == W8 || w == W16-> do       (reg_x, _format_x, code_x) <- getSomeReg x       (reg_y, _format_y, code_y) <- getSomeReg y-      return $ Any (intFormat w) (\dst -> code_x `appOL` code_y `snocOL` annExpr expr (UXTH (OpReg w reg_x) (OpReg w reg_x)) `snocOL`-                                                                        (UXTH (OpReg w reg_y) (OpReg w reg_y)) `snocOL`-                                                                        (UDIV (OpReg w dst) (OpReg w reg_x) (OpReg w reg_y)))+      return $ Any (intFormat w) (\dst -> code_x `appOL` code_y `snocOL` annExpr expr (UDIV (OpReg w dst) (OpReg w reg_x) (OpReg w reg_y)))      -- 2. Shifts. x << n, x >> n.+    -- Sub-word left shifts by a constant: use UBFM (UBFIZ alias) to shift+    -- and mask in a single instruction.  See Note [Subword operations on AArch64].+    CmmMachOp (MO_Shl w) [x, (CmmLit (CmmInt n _))] | w == W8, 0 <= n, n < 8 -> do+      (reg_x, _format_x, code_x) <- getSomeReg x+      return $ Any (intFormat w) (\dst -> code_x `snocOL` annExpr expr (UBFM (OpReg w dst) (OpReg w reg_x) (OpImm (ImmInteger ((32 - n) `mod` 32))) (OpImm (ImmInteger (7 - n)))))+    CmmMachOp (MO_Shl w) [x, (CmmLit (CmmInt n _))] | w == W16, 0 <= n, n < 16 -> do+      (reg_x, _format_x, code_x) <- getSomeReg x+      return $ Any (intFormat w) (\dst -> code_x `snocOL` annExpr expr (UBFM (OpReg w dst) (OpReg w reg_x) (OpImm (ImmInteger ((32 - n) `mod` 32))) (OpImm (ImmInteger (15 - n)))))+     CmmMachOp (MO_Shl w) [x, (CmmLit (CmmInt n _))]       | w == W32 || w == W64       , 0 <= n, n < fromIntegral (widthInBits w) -> do@@ -929,24 +963,30 @@     CmmMachOp (MO_S_Shr w) [x, (CmmLit (CmmInt n _))] | w == W8, 0 <= n, n < 8 -> do       (reg_x, _format_x, code_x) <- getSomeReg x       return $ Any (intFormat w) (\dst -> code_x `snocOL` annExpr expr (SBFX (OpReg w dst) (OpReg w reg_x) (OpImm (ImmInteger n)) (OpImm (ImmInteger (8-n))))-                                                 `snocOL` (UXTB (OpReg w dst) (OpReg w dst))) -- See Note [Signed arithmetic on AArch64]+                                                 `snocOL` (UXTB (OpReg w dst) (OpReg w dst))) -- See Note [Subword operations on AArch64]     CmmMachOp (MO_S_Shr w) [x, y] | w == W8 -> do       (reg_x, _format_x, code_x) <- getSomeReg x       (reg_y, _format_y, code_y) <- getSomeReg y-      return $ Any (intFormat w) (\dst -> code_x `appOL` code_y `snocOL` annExpr expr (SXTB (OpReg w reg_x) (OpReg w reg_x)) `snocOL`-                                                                         (ASR (OpReg w dst) (OpReg w reg_x) (OpReg w reg_y)) `snocOL`-                                                                         (UXTB (OpReg w dst) (OpReg w dst))) -- See Note [Signed arithmetic on AArch64]+      -- Use a temporary register to avoid sign-extending reg_x in-place,+      -- as other operations may use reg_x.+      tmp <- getNewRegNat (intFormat w)+      return $ Any (intFormat w) (\dst -> code_x `appOL` code_y `snocOL` annExpr expr (SXTB (OpReg w tmp) (OpReg w reg_x)) `snocOL`+                                                                         (ASR (OpReg w dst) (OpReg w tmp) (OpReg w reg_y)) `snocOL`+                                                                         (UXTB (OpReg w dst) (OpReg w dst))) -- See Note [Subword operations on AArch64]      CmmMachOp (MO_S_Shr w) [x, (CmmLit (CmmInt n _))] | w == W16, 0 <= n, n < 16 -> do       (reg_x, _format_x, code_x) <- getSomeReg x       return $ Any (intFormat w) (\dst -> code_x `snocOL` annExpr expr (SBFX (OpReg w dst) (OpReg w reg_x) (OpImm (ImmInteger n)) (OpImm (ImmInteger (16-n))))-                                                 `snocOL` (UXTH (OpReg w dst) (OpReg w dst))) -- See Note [Signed arithmetic on AArch64]+                                                 `snocOL` (UXTH (OpReg w dst) (OpReg w dst))) -- See Note [Subword operations on AArch64]     CmmMachOp (MO_S_Shr w) [x, y] | w == W16 -> do       (reg_x, _format_x, code_x) <- getSomeReg x       (reg_y, _format_y, code_y) <- getSomeReg y-      return $ Any (intFormat w) (\dst -> code_x `appOL` code_y `snocOL` annExpr expr (SXTH (OpReg w reg_x) (OpReg w reg_x)) `snocOL`-                                                                         (ASR (OpReg w dst) (OpReg w reg_x) (OpReg w reg_y)) `snocOL`-                                                                         (UXTH (OpReg w dst) (OpReg w dst))) -- See Note [Signed arithmetic on AArch64]+      -- Use a temporary register to avoid sign-extending reg_x in-place,+      -- as other operations may use reg_x.+      tmp <- getNewRegNat (intFormat w)+      return $ Any (intFormat w) (\dst -> code_x `appOL` code_y `snocOL` annExpr expr (SXTH (OpReg w tmp) (OpReg w reg_x)) `snocOL`+                                                                         (ASR (OpReg w dst) (OpReg w tmp) (OpReg w reg_y)) `snocOL`+                                                                         (UXTH (OpReg w dst) (OpReg w dst))) -- See Note [Subword operations on AArch64]      CmmMachOp (MO_S_Shr w) [x, (CmmLit (CmmInt n _))]       | w == W32 || w == W64@@ -960,8 +1000,8 @@     CmmMachOp (MO_U_Shr w) [x, y] | w == W8 -> do       (reg_x, _format_x, code_x) <- getSomeReg x       (reg_y, _format_y, code_y) <- getSomeReg y-      return $ Any (intFormat w) (\dst -> code_x `appOL` code_y `snocOL` annExpr expr (UXTB (OpReg w reg_x) (OpReg w reg_x)) `snocOL`-                                                                        (ASR (OpReg w dst) (OpReg w reg_x) (OpReg w reg_y)))+      tmp <- getNewRegNat (intFormat w)+      return $ Any (intFormat w) (\dst -> code_x `appOL` code_y `snocOL` UXTB (OpReg w tmp) (OpReg w reg_x) `snocOL` annExpr expr (LSR (OpReg w dst) (OpReg w tmp) (OpReg w reg_y)))      CmmMachOp (MO_U_Shr w) [x, (CmmLit (CmmInt n _))] | w == W16, 0 <= n, n < 16 -> do       (reg_x, _format_x, code_x) <- getSomeReg x@@ -969,8 +1009,8 @@     CmmMachOp (MO_U_Shr w) [x, y] | w == W16 -> do       (reg_x, _format_x, code_x) <- getSomeReg x       (reg_y, _format_y, code_y) <- getSomeReg y-      return $ Any (intFormat w) (\dst -> code_x `appOL` code_y `snocOL` annExpr expr (UXTH (OpReg w reg_x) (OpReg w reg_x))-                                                                `snocOL` (ASR (OpReg w dst) (OpReg w reg_x) (OpReg w reg_y)))+      tmp <- getNewRegNat (intFormat w)+      return $ Any (intFormat w) (\dst -> code_x `appOL` code_y `snocOL` UXTH (OpReg w tmp) (OpReg w reg_x) `snocOL` annExpr expr (LSR (OpReg w dst) (OpReg w tmp) (OpReg w reg_y)))      CmmMachOp (MO_U_Shr w) [x, (CmmLit (CmmInt n _))]       | w == W32 || w == W64@@ -979,14 +1019,16 @@       return $ Any (intFormat w) (\dst -> code_x `snocOL` annExpr expr (LSR (OpReg w dst) (OpReg w reg_x) (OpImm (ImmInteger n))))      -- 3. Logic &&, ||-    CmmMachOp (MO_And w) [(CmmReg reg), CmmLit (CmmInt n _)] | isAArch64Bitmask (opRegWidth w') (fromIntegral n) ->-      return $ Any (intFormat w) (\d -> unitOL $ annExpr expr (AND (OpReg w d) (OpReg w' r') (OpImm (ImmInteger n))))-      where w' = formatToWidth (cmmTypeFormat (cmmRegType reg))+    CmmMachOp (MO_And w) [(CmmReg reg), CmmLit (CmmInt n _)] | Just op_bitmask <- getBitmaskImm n w ->+      return $ Any fmt (\d -> unitOL $ annExpr expr (AND (OpReg w d) (OpReg w' r') op_bitmask))+      where fmt = intFormat w+            w' = formatToWidth (cmmTypeFormat (cmmRegType reg))             r' = getRegisterReg plat reg -    CmmMachOp (MO_Or w) [(CmmReg reg), CmmLit (CmmInt n _)] | isAArch64Bitmask (opRegWidth w') (fromIntegral n) ->-      return $ Any (intFormat w) (\d -> unitOL $ annExpr expr (ORR (OpReg w d) (OpReg w' r') (OpImm (ImmInteger n))))-      where w' = formatToWidth (cmmTypeFormat (cmmRegType reg))+    CmmMachOp (MO_Or w) [(CmmReg reg), CmmLit (CmmInt n _)] | Just op_bitmask <- getBitmaskImm n w ->+      return $ Any fmt (\d -> unitOL $ annExpr expr (ORR (OpReg w d) (OpReg w' r') op_bitmask))+      where fmt = intFormat w+            w' = formatToWidth (cmmTypeFormat (cmmRegType reg))             r' = getRegisterReg plat reg      -- Generic binary case.@@ -1015,16 +1057,17 @@                 code_y `appOL`                 op (OpReg w dst) (OpReg w reg_x) op_y) -          -- A (potentially signed) integer operation.+          -- A (potentially signed) integer operation that can have immediate arguments.           -- In the case of 8- and 16-bit signed arithmetic we must first           -- sign-extend both arguments to 32-bits.-          -- See Note [Signed arithmetic on AArch64].-          intOpImm :: Bool -> Width -> (Operand -> Operand -> Operand -> OrdList Instr) -> (Integer -> Width -> Maybe Operand) -> NatM (Register)-          intOpImm {- is signed -} True  w op _encode_imm = intOp True w op-          intOpImm                 False w op  encode_imm = do+          -- See Note [Subword operations on AArch64].+          intOpImm :: Bool -> SetsHighBits -> Width -> (Operand -> Operand -> Operand -> OrdList Instr) -> (Integer -> Width -> Maybe Operand) -> NatM (Register)+          intOpImm {- is signed -} True  trunc w op _encode_imm = intOp True trunc w op+          intOpImm                 False trunc w op  encode_imm = maintainHighBits trunc w <$> do               -- compute x<m> <- x               -- compute x<o> <- y               -- <OP> x<n>, x<m>, x<o>+              let w' = opRegWidth w               (reg_x, format_x, code_x) <- getSomeReg x               (op_y, format_y, code_y) <- case y of                 CmmLit (CmmInt n w)@@ -1036,40 +1079,29 @@               massertPpr (isIntFormat format_x && isIntFormat format_y) $ text "intOp: non-int"               -- This is the width of the registers on which the operation               -- should be performed.-              let w' = opRegWidth w               return $ Any (intFormat w) $ \dst ->                   code_x `appOL`                   code_y `appOL`-                  op (OpReg w' dst) (OpReg w' reg_x) (op_y) `appOL`-                  truncateReg w' w dst -- truncate back to the operand's original width+                  op (OpReg w' dst) (OpReg w' reg_x) (op_y)            -- A (potentially signed) integer operation.           -- In the case of 8- and 16-bit signed arithmetic we must first           -- sign-extend both arguments to 32-bits.-          -- See Note [Signed arithmetic on AArch64].-          intOp is_signed w op = do+          -- See Note [Subword operations on AArch64].+          intOp is_signed clean_highbits w op = maintainHighBits clean_highbits w <$> do               -- compute x<m> <- x               -- compute x<o> <- y               -- <OP> x<n>, x<m>, x<o>-              (reg_x, format_x, code_x) <- getSomeReg x-              (reg_y, format_y, code_y) <- getSomeReg y+              let op_w = opRegWidth w+              let setHighBits = if is_signed then signExtendRegister w (opRegWidth w) else id+              (reg_x_sx, format_x, code_x) <- someReg =<< setHighBits <$> getRegister x+              (reg_y_sx, format_y, code_y) <- someReg =<< setHighBits <$> getRegister y               massertPpr (isIntFormat format_x && isIntFormat format_y) $ text "intOp: non-int"-              -- This is the width of the registers on which the operation-              -- should be performed.-              let w' = opRegWidth w-                  signExt r-                    | not is_signed  = return (r, nilOL)-                    | otherwise      = signExtendReg w w' r-              (reg_x_sx, code_x_sx) <- signExt reg_x-              (reg_y_sx, code_y_sx) <- signExt reg_y+               return $ Any (intFormat w) $ \dst ->                   code_x `appOL`                   code_y `appOL`-                  -- sign-extend both operands-                  code_x_sx `appOL`-                  code_y_sx `appOL`-                  op (OpReg w' dst) (OpReg w' reg_x_sx) (OpReg w' reg_y_sx) `appOL`-                  truncateReg w' w dst -- truncate back to the operand's original width+                  op (OpReg op_w dst) (OpReg op_w reg_x_sx) (OpReg op_w reg_y_sx)            floatOp w op = do             (reg_fx, format_x, code_fx) <- getFloatReg x@@ -1087,9 +1119,9 @@       case op of         -- Integer operations         -- Add/Sub should only be Integer Options.-        MO_Add w -> intOpImm False w (\d x y -> unitOL $ annExpr expr (ADD d x y)) getArithImm+        MO_Add w -> intOpImm False UnknownHighBits w (\d x y -> unitOL $ annExpr expr (ADD d x y)) getArithImm         -- TODO: Handle sub-word case-        MO_Sub w -> intOpImm False w (\d x y -> unitOL $ annExpr expr (SUB d x y)) getArithImm+        MO_Sub w -> intOpImm False UnknownHighBits w (\d x y -> unitOL $ annExpr expr (SUB d x y)) getArithImm          -- Note [CSET]         -- ~~~~~~~~~~~@@ -1135,9 +1167,9 @@         MO_Ne w     -> bitOpImm w (\d x y -> toOL [ CMP x y, CSET d NE ]) getArithImm          -- Signed multiply/divide-        MO_Mul w          -> intOp True w (\d x y -> unitOL $ MUL d x y)+        MO_Mul w          -> intOp True UnknownHighBits w (\d x y -> unitOL $ MUL d x y)         MO_S_MulMayOflo w -> do_mul_may_oflo w x y-        MO_S_Quot w       -> intOp True w (\d x y -> unitOL $ SDIV d x y)+        MO_S_Quot w       -> intOp True UnknownHighBits w (\d x y -> unitOL $ SDIV d x y)          -- No native rem instruction. So we'll compute the following         -- Rd  <- Rx / Ry             | 2 <- 7 / 3      -- SDIV Rd Rx Ry@@ -1147,24 +1179,24 @@         --        '--------------------------'         -- Note the swap in Rx and Ry.         MO_S_Rem w -> withTempIntReg w $ \t ->-                      intOp True w (\d x y -> toOL [ SDIV t x y, MSUB d t y x ])+                      intOp True UnknownHighBits w (\d x y -> toOL [ SDIV t x y, MSUB d t y x ])          -- Unsigned multiply/divide-        MO_U_Quot w -> intOp False w (\d x y -> unitOL $ UDIV d x y)+        MO_U_Quot w -> intOp False CleanHighBits w (\d x y -> unitOL $ UDIV d x y)         MO_U_Rem w  -> withTempIntReg w $ \t ->-                       intOp False w (\d x y -> toOL [ UDIV t x y, MSUB d t y x ])+                       intOp False CleanHighBits w (\d x y -> toOL [ UDIV t x y, MSUB d t y x ])          -- Signed comparisons -- see Note [CSET]-        MO_S_Ge w     -> intOp True  w (\d x y -> toOL [ CMP x y, CSET d SGE ])-        MO_S_Le w     -> intOp True  w (\d x y -> toOL [ CMP x y, CSET d SLE ])-        MO_S_Gt w     -> intOp True  w (\d x y -> toOL [ CMP x y, CSET d SGT ])-        MO_S_Lt w     -> intOp True  w (\d x y -> toOL [ CMP x y, CSET d SLT ])+        MO_S_Ge w     -> intOp True CleanHighBits w (\d x y -> toOL [ CMP x y, CSET d SGE ])+        MO_S_Le w     -> intOp True CleanHighBits w (\d x y -> toOL [ CMP x y, CSET d SLE ])+        MO_S_Gt w     -> intOp True CleanHighBits w (\d x y -> toOL [ CMP x y, CSET d SGT ])+        MO_S_Lt w     -> intOp True CleanHighBits w (\d x y -> toOL [ CMP x y, CSET d SLT ])          -- Unsigned comparisons-        MO_U_Ge w     -> intOpImm False w (\d x y -> toOL [ CMP x y, CSET d UGE ]) getArithImm-        MO_U_Le w     -> intOpImm False w (\d x y -> toOL [ CMP x y, CSET d ULE ]) getArithImm-        MO_U_Gt w     -> intOpImm False w (\d x y -> toOL [ CMP x y, CSET d UGT ]) getArithImm-        MO_U_Lt w     -> intOpImm False w (\d x y -> toOL [ CMP x y, CSET d ULT ]) getArithImm+        MO_U_Ge w     -> intOpImm False CleanHighBits w (\d x y -> toOL [ CMP x y, CSET d UGE ]) getArithImm+        MO_U_Le w     -> intOpImm False CleanHighBits w (\d x y -> toOL [ CMP x y, CSET d ULE ]) getArithImm+        MO_U_Gt w     -> intOpImm False CleanHighBits w (\d x y -> toOL [ CMP x y, CSET d UGT ]) getArithImm+        MO_U_Lt w     -> intOpImm False CleanHighBits w (\d x y -> toOL [ CMP x y, CSET d ULT ]) getArithImm          -- Floating point arithmetic         MO_F_Add w   -> floatOp w (\d x y -> unitOL $ ADD d x y)@@ -1192,9 +1224,9 @@         MO_And   w -> bitOpImm w (\d x y -> unitOL $ AND d x y) getBitmaskImm         MO_Or    w -> bitOpImm w (\d x y -> unitOL $ ORR d x y) getBitmaskImm         MO_Xor   w -> bitOpImm w (\d x y -> unitOL $ EOR d x y) getBitmaskImm-        MO_Shl   w -> intOp False w (\d x y -> unitOL $ LSL d x y)-        MO_U_Shr w -> intOp False w (\d x y -> unitOL $ LSR d x y)-        MO_S_Shr w -> intOp True  w (\d x y -> unitOL $ ASR d x y)+        MO_Shl   w -> intOp False UnknownHighBits w (\d x y -> unitOL $ LSL d x y)+        MO_U_Shr w -> intOp False CleanHighBits w (\d x y -> unitOL $ LSR d x y)+        MO_S_Shr w -> intOp True  UnknownHighBits w (\d x y -> unitOL $ ASR d x y)          -- Non-dyadic MachOp with 2 arguments         MO_S_Neg {} -> notDyadic@@ -1388,37 +1420,88 @@     hasOneRun m =         64 == popCount m + countLeadingZeros m + countTrailingZeros m +--------------------------------------------------------------------------------+-- Helpers to help enforcing Note [Subword operations on AArch64]+--------------------------------------------------------------------------------+ -- | Instructions to sign-extend the value in the given register from width @w@ -- up to width @w'@.-signExtendReg :: Width -> Width -> Reg -> NatM (Reg, OrdList Instr)-signExtendReg w w' r =-    case w of-      W64 -> noop-      W32-        | w' == W32 -> noop-        | otherwise -> extend SXTH-      W16           -> extend SXTH-      W8            -> extend SXTB-      _             -> panic "intOp"+signExtendInstr :: Width -> Width -> Reg -> Maybe (Reg -> Instr)+signExtendInstr w w' r =+    case (w,w') of+      (W64,_) -> Nothing+      (W32,W32) -> Nothing+      (W32,_) -> extend SXTW+      (W16,_) -> extend SXTH+      (W8 ,_) -> extend SXTB+      _             -> panic "signExtendInstr:unexpectedWidth"   where-    noop = return (r, nilOL)-    extend instr = do-        r' <- getNewRegNat II64-        return (r', unitOL $ instr (OpReg w' r') (OpReg w' r))+    extend instr = Just $ \r' -> instr (OpReg w' r') (OpReg w r) --- | Instructions to truncate the value in the given register from width @w@--- down to width @w'@.-truncateReg :: Width -> Width -> Reg -> OrdList Instr-truncateReg w w' r =-    case w of+-- | Sign extend the register if needed, otherwise use register as-is+signExtendRegister :: Width -> Width -> Register -> Register+signExtendRegister w w' register = case register of+  Fixed _fmt reg code ->+    maybe register+      (\instr_ext -> Any (intFormat w') (\dst -> code `snocOL` instr_ext dst) )+      (signExtendInstr w w' reg)+  Any _fmt code ->+    Any (intFormat w') $ \dst ->+      maybe (code dst)+        (\instr_ext -> code dst `snocOL` instr_ext dst)+        (signExtendInstr w w' dst)++truncSubwordRegInstr :: Width -> Reg -> Maybe (Reg -> Instr)+truncSubwordRegInstr w_to r =+    case w_to of+      -- Asserted false, but be defensive for non-debug builds.+      W64 -> Nothing+      W32 -> Nothing++      -- Actual truncation+      W16 -> trunc W32 UXTH+      W8  -> trunc W32 UXTB+      _   -> panic "truncateSubwordReg:unexpectedWidth"+  where+    trunc w instr = do+        Just $ \r' -> instr (OpReg w r') (OpReg w r)++-- | Like @truncateSubwordRegister@, but modifes the given argument register in place if we+-- need to truncate.+truncateSubwordRegInplace :: Width -> Reg -> OrdList Instr+truncateSubwordRegInplace w_to r = do+    case w_to of       W64 -> nilOL-      W32-        | w' == W32 -> nilOL-      _   -> unitOL $ UBFM (OpReg w r)-                           (OpReg w r)-                           (OpImm (ImmInt 0))-                           (OpImm $ ImmInt $ widthInBits w' - 1)+      W32 -> nilOL+      W16 -> trunc UXTH+      W8  -> trunc UXTB+      _   -> panic "truncateSubwordRegInplace:unexpectedWidth"+  where+    trunc instr = do+        unitOL $ instr (OpReg W32 r) (OpReg W32 r) +-- | Zeros the high words of the value represented by Register if needed according to+-- Note [Subword operations on AArch64]+truncateSubwordRegister :: Width -> Register -> Register+truncateSubwordRegister w register = case register of+  Fixed _fmt reg code ->+    maybe (swizzleRegisterRep register (intFormat w))+      (\r_instr -> Any (intFormat w) (\dst -> code `snocOL` r_instr dst))+      (truncSubwordRegInstr w reg)+  Any _fmt code -> Any (intFormat w) $ \dst ->+    maybe (code dst) (\r_inst -> code dst `snocOL` r_inst dst) (truncSubwordRegInstr w dst)++data SetsHighBits = UnknownHighBits | CleanHighBits++maintainHighBits :: SetsHighBits -> Width -> Register -> Register+maintainHighBits CleanHighBits _w x = x+maintainHighBits UnknownHighBits w x = truncateSubwordRegister w x++-- Reinterpret the value in the register as different format.+swizzleRegisterRep :: Register -> Format -> Register+swizzleRegisterRep (Fixed _ reg code) format = Fixed format reg code+swizzleRegisterRep (Any _ codefn)     format = Any   format codefn+ -- ----------------------------------------------------------------------------- --  The 'Amode' type: Memory addressing modes passed up the tree. data Amode = Amode AddrMode InstrBlock@@ -1547,28 +1630,25 @@       -- Generic case.       CmmMachOp mop [x, y] -> do -        let ubcond w cmp = do-                -- compute both sides.-                (reg_x, _format_x, code_x) <- getSomeReg x-                (reg_y, _format_y, code_y) <- getSomeReg y-                let x' = OpReg w reg_x-                    y' = OpReg w reg_y-                return $ case w of-                  W8  -> code_x `appOL` code_y `appOL` toOL [ UXTB x' x', UXTB y' y', CMP x' y', (annExpr expr (BCOND cmp (TBlock bid))) ]-                  W16 -> code_x `appOL` code_y `appOL` toOL [ UXTH x' x', UXTH y' y', CMP x' y', (annExpr expr (BCOND cmp (TBlock bid))) ]-                  _   -> code_x `appOL` code_y `appOL` toOL [                         CMP x' y', (annExpr expr (BCOND cmp (TBlock bid))) ]+        let icond is_signed w cmp = do+                -- zero or sign extend the argument register(s)+                let extend reg =+                      if is_signed+                        then someReg $ signExtendRegister w (opRegWidth w) reg+                        else someReg reg -            sbcond w cmp = do-                -- compute both sides.-                (reg_x, _format_x, code_x) <- getSomeReg x-                (reg_y, _format_y, code_y) <- getSomeReg y+                (reg_x, _format_x, code_x) <- extend =<< getRegister x+                (reg_y, _format_y, code_y) <- extend =<< getRegister y+                 let x' = OpReg w reg_x                     y' = OpReg w reg_y-                return $ case w of-                  W8  -> code_x `appOL` code_y `appOL` toOL [ SXTB x' x', SXTB y' y', CMP x' y', (annExpr expr (BCOND cmp (TBlock bid))) ]-                  W16 -> code_x `appOL` code_y `appOL` toOL [ SXTH x' x', SXTH y' y', CMP x' y', (annExpr expr (BCOND cmp (TBlock bid))) ]-                  _   -> code_x `appOL` code_y `appOL` toOL [                         CMP x' y', (annExpr expr (BCOND cmp (TBlock bid))) ] +                return $ concatOL [code_x, code_y,+                                   toOL [CMP x' y', (annExpr expr (BCOND cmp (TBlock bid)))]]++        let ubcond w cmp = icond False w cmp+            sbcond w cmp = icond True  w cmp+             fbcond w cmp = do               -- ensure we get float regs               (reg_fx, _format_fx, code_fx) <- getFloatReg x@@ -1809,11 +1889,19 @@               let lo = getRegisterReg platform (CmmLocal dst_lo)                   hi = getRegisterReg platform (CmmLocal dst_hi)                   nd = getRegisterReg platform (CmmLocal dst_needed)++              -- Generate a fresh virtual register for the low word computation.+              -- This avoids clobbering reg_a or reg_b in the first MUL instruction,+              -- which could for example happen if 'lo' and 'reg_a' are the same+              -- virtual register.+              tmp_lo <- getNewRegNat II64+               return $                   code_x `appOL`                   code_y `snocOL`-                  MUL   (OpReg W64 lo) (OpReg W64 reg_a) (OpReg W64 reg_b) `snocOL`+                  MUL   (OpReg W64 tmp_lo) (OpReg W64 reg_a) (OpReg W64 reg_b) `snocOL`                   SMULH (OpReg W64 hi) (OpReg W64 reg_a) (OpReg W64 reg_b) `snocOL`+                  MOV   (OpReg W64 lo) (OpReg W64 tmp_lo) `snocOL`                   -- Are all high bits equal to the sign bit of the low word?                   -- nd = (hi == ASR(lo,width-1)) ? 1 : 0                   CMP   (OpReg W64 hi) (OpRegShift W64 lo SASR (widthInBits w - 1)) `snocOL`@@ -1828,48 +1916,37 @@           , [src_a, src_b] <- arg_regs           , [dst_needed, dst_hi, dst_lo] <- dest_regs             ->  do-              (reg_a', _format_x, code_a) <- getSomeReg src_a-              (reg_b', _format_y, code_b) <- getSomeReg src_b+              -- Sign-extend inputs to W32 for SMULL (Xd = Wn * Wm).+              -- sign extension always allocates a fresh temp for w < W32,+              -- and is a noop for W32 (safe: SMULL reads both sources+              -- atomically before writing the destination).+              (reg_a, _format_x, code_a) <- someReg =<< signExtendRegister w W32 <$> getRegister src_a+              (reg_b, _format_y, code_b) <- someReg =<< signExtendRegister w W32 <$> getRegister src_b                let lo = getRegisterReg platform (CmmLocal dst_lo)                   hi = getRegisterReg platform (CmmLocal dst_hi)                   nd = getRegisterReg platform (CmmLocal dst_needed)-                  -- Do everything in a full 64 bit registers                   w' = platformWordWidth platform -              (reg_a, code_a') <- signExtendReg w w' reg_a'-              (reg_b, code_b') <- signExtendReg w w' reg_b'-               return $                   code_a  `appOL`-                  code_b  `appOL`-                  code_a' `appOL`-                  code_b' `snocOL`-                  -- the low 2w' of lo contains the full multiplication;-                  -- eg: int8 * int8 -> int16 result-                  -- so lo is in the last w of the register, and hi is in the second w.-                  SMULL (OpReg w' lo) (OpReg w' reg_a) (OpReg w' reg_b) `snocOL`-                  -- Make sure we hold onto the sign bits for dst_needed-                  ASR (OpReg w' hi) (OpReg w' lo)    (OpImm (ImmInt $ widthInBits w)) `appOL`-                  -- lo can now be truncated so we can get at it's top bit easily.-                  truncateReg w' w lo `snocOL`-                  -- Note the use of CMN (compare negative), not CMP: we want to-                  -- test if the top half is negative one and the top-                  -- bit of the bottom half is positive one. eg:-                  -- hi = 0b1111_1111  (actually 64 bits)-                  -- lo = 0b1010_1111  (-81, so the result didn't need the top half)-                  -- lo' = ASR(lo,7)   (second reg of SMN)-                  --     = 0b0000_0001 (theeshift gives us 1 for negative,-                  --                    and 0 for positive)-                  -- hi == -lo'?-                  -- 0b1111_1111 == 0b1111_1111 (yes, top half is just overflow)-                  -- Another way to think of this is if hi + lo' == 0, which is what-                  -- CMN really is under the hood.+                  code_b  `snocOL`+                  -- SMULL Xd, Wn, Wm: multiply two W32 values producing a+                  -- 64-bit result. The low w bits of lo contain the truncated+                  -- product, and hi gets the overflow (sign extension bits).+                  SMULL (OpReg w' lo) (OpReg W32 reg_a) (OpReg W32 reg_b) `snocOL`+                  ASR (OpReg w' hi) (OpReg w' lo) (OpImm (ImmInt $ widthInBits w)) `appOL`+                  truncateSubwordRegInplace w lo `snocOL`+                  -- CMN (compare negative) tests hi + lo' == 0, i.e. hi == -lo'.+                  -- lo' = LSR(lo, w-1) gives 1 if lo is negative, 0 if positive.+                  -- No overflow iff hi is the sign extension of lo:+                  --   lo positive (bit w-1 = 0) => lo' = 0, need hi == 0+                  --   lo negative (bit w-1 = 1) => lo' = 1, need hi == -1+                  -- CMN sets Z when hi + lo' == 0 (no overflow), so we use+                  -- NE to set nd = 1 when overflow occurred.                   CMN   (OpReg w' hi) (OpRegShift w' lo SLSR (widthInBits w - 1)) `snocOL`-                  -- Set dst_needed to 1 if hi and lo' were (negatively) equal-                  CSET  (OpReg w' nd) EQ `appOL`-                  -- Finally truncate hi to drop any extraneous sign bits.-                  truncateReg w' w hi+                  CSET  (OpReg w' nd) NE `appOL`+                  truncateSubwordRegInplace w hi           -- Can't handle > 64 bit operands           | otherwise -> unsupported (MO_S_Mul2 w)     PrimTarget (MO_U_Mul2  w)@@ -1892,7 +1969,7 @@                   )             -- For sizes < platform width, we can just perform a multiply and shift             -- Need to be careful to truncate the low half, but the upper half should be-            -- be ok if the invariant in [Signed arithmetic on AArch64] is maintained.+            -- be ok if the invariant in Note [Subword operations on AArch64] is maintained.             -- Currently this case can't be produced by the compiler since             -- timesWord2# :: Word# -> Word# -> (# Word#, Word# #)             -- TODO: Remove? Or would the extra primop be useful for avoiding the extra@@ -1919,7 +1996,7 @@                       (OpImm (ImmInt $ widthInBits w)) -- lsb                       (OpImm (ImmInt $ widthInBits w)) -- width to extract                       `appOL`-                  truncateReg W64 w lo+                  truncateSubwordRegInplace w lo                   )           | otherwise -> unsupported (MO_U_Mul2  w)     PrimTarget (MO_Clz  w)@@ -2220,6 +2297,7 @@           | [p_reg, val_reg] <- arg_regs -> do               (p, _fmt_p, code_p) <- getSomeReg p_reg               (val, fmt_val, code_val) <- getSomeReg val_reg+              massert (fmt_val == intFormat w)               let instr = case ord of                       MemOrderRelaxed -> STR                       _               -> STLR@@ -2335,6 +2413,7 @@                 W16 -> SXTH (OpReg W64 gpReg) (OpReg w r)                 _   -> panic "impossible"             | otherwise+            -- Relies on Note [Subword operations on AArch64]             = MOV (OpReg w gpReg) (OpReg w r)           accumCode' = accumCode `appOL`                        code_r `snocOL`@@ -2388,6 +2467,7 @@      passArguments _ _ _ _ _ _ _ = pprPanic "passArguments" (text "invalid state") +    -- readResults gpArgs fpArgs dest_regs reg_acc code_acc     readResults :: [Reg] -> [Reg] -> [LocalReg] -> [Reg]-> InstrBlock -> NatM (InstrBlock)     readResults _ _ [] _ accumCode = return accumCode     readResults [] _ _ _ _ = do@@ -2405,7 +2485,14 @@           r_dst = getRegisterReg platform (CmmLocal dst)       if isFloatFormat format         then readResults (gpReg:gpRegs) fpRegs dsts (fpReg:accumRegs) (accumCode `snocOL` MOV (OpReg w r_dst) (OpReg w fpReg))-        else readResults gpRegs (fpReg:fpRegs) dsts (gpReg:accumRegs) (accumCode `snocOL` MOV (OpReg w r_dst) (OpReg w gpReg))+        else do+          -- Needed, ffi calls can return garbage in high bits.+          -- See Note [Subword operations on AArch64]+          let !mov_instr = case w of+                W8  -> UXTB+                W16 -> UXTH+                _   -> MOV+          readResults gpRegs (fpReg:fpRegs) dsts (gpReg:accumRegs) (accumCode `snocOL` mov_instr (OpReg w r_dst) (OpReg w gpReg))      unaryFloatOp w op arg_reg dest_reg = do       platform <- getPlatform
GHC/CmmToAsm/AArch64/Instr.hs view
@@ -101,6 +101,7 @@   SXTB dst src             -> usage (regOp src, regOp dst)   UXTB dst src             -> usage (regOp src, regOp dst)   SXTH dst src             -> usage (regOp src, regOp dst)+  SXTW dst src             -> usage (regOp src, regOp dst)   UXTH dst src             -> usage (regOp src, regOp dst)   CLZ  dst src             -> usage (regOp src, regOp dst)   RBIT dst src             -> usage (regOp src, regOp dst)@@ -114,7 +115,7 @@   LSL dst src1 src2        -> usage (regOp src1 ++ regOp src2, regOp dst)   LSR dst src1 src2        -> usage (regOp src1 ++ regOp src2, regOp dst)   MOV dst src              -> usage (regOp src, regOp dst)-  MOVK dst src             -> usage (regOp src, regOp dst)+  MOVK dst src             -> usage (regOp src ++ regOp dst, regOp dst)   MOVZ dst src             -> usage (regOp src, regOp dst)   MVN dst src              -> usage (regOp src, regOp dst)   ORR dst src1 src2        -> usage (regOp src1 ++ regOp src2, regOp dst)@@ -255,6 +256,7 @@     SXTB o1 o2       -> SXTB (patchOp o1) (patchOp o2)     UXTB o1 o2       -> UXTB (patchOp o1) (patchOp o2)     SXTH o1 o2       -> SXTH (patchOp o1) (patchOp o2)+    SXTW o1 o2       -> SXTW (patchOp o1) (patchOp o2)     UXTH o1 o2       -> UXTH (patchOp o1) (patchOp o2)     CLZ o1 o2        -> CLZ  (patchOp o1) (patchOp o2)     RBIT o1 o2       -> RBIT (patchOp o1) (patchOp o2)@@ -594,8 +596,7 @@     | UXTB Operand Operand     | SXTH Operand Operand     | UXTH Operand Operand-    -- | SXTW Operand Operand-    -- | SXTX Operand Operand+    | SXTW Operand Operand     | PUSH_STACK_FRAME     | POP_STACK_FRAME     -- 1. Arithmetic Instructions ----------------------------------------------@@ -664,7 +665,8 @@     | MOVZ Operand Operand     | MVN Operand Operand -- rd = ~rn     | ORR Operand Operand Operand -- rd = rn | op2-    -- Load and stores.+    -- Load and stores, we support subwords by picking the subword variant+    -- based on the format.     -- TODO STR/LDR might want to change to STP/LDP with XZR for the second register.     | STR Format Operand Operand -- str Xn, address-mode // Xn -> *addr     | STLR Format Operand Operand -- stlr Xn, address-mode // Xn -> *addr@@ -726,6 +728,7 @@       SXTB{} -> "SXTB"       UXTB{} -> "UXTB"       SXTH{} -> "SXTH"+      SXTW{} -> "SXTW"       UXTH{} -> "UXTH"       PUSH_STACK_FRAME{} -> "PUSH_STACK_FRAME"       POP_STACK_FRAME{} -> "POP_STACK_FRAME"
GHC/CmmToAsm/AArch64/Ppr.hs view
@@ -19,6 +19,7 @@  import GHC.Cmm.BlockId import GHC.Cmm.CLabel+import GHC.Cmm.InitFini  import GHC.Types.Unique ( pprUniqueAlways, getUnique ) import GHC.Platform@@ -28,9 +29,7 @@  pprNatCmmDecl :: IsDoc doc => NCGConfig -> NatCmmDecl RawCmmStatics Instr -> doc pprNatCmmDecl config (CmmData section dats) =-  let platform = ncgPlatform config-  in-  pprSectionAlign config section $$ pprDatas platform dats+  pprSectionAlign config section $$ pprDatas config dats  pprNatCmmDecl config proc@(CmmProc top_info lbl _ (ListGraph blocks)) =   let platform = ncgPlatform config@@ -93,9 +92,20 @@ pprSectionAlign :: IsDoc doc => NCGConfig -> Section -> doc pprSectionAlign _config (Section (OtherSection _) _) =      panic "AArch64.Ppr.pprSectionAlign: unknown section"-pprSectionAlign config sec@(Section seg _) =+pprSectionAlign config sec@(Section seg suffix) =     line (pprSectionHeader config sec)+    $$ coffSplitSectionComdatKey     $$ pprAlignForSection (ncgPlatform config) seg+  where+    platform = ncgPlatform config+    -- See Note [Split sections on COFF objects]+    coffSplitSectionComdatKey+      | OSMinGW32 <- platformOS platform+      , ncgSplitSections config+      , Nothing <- isInitOrFiniSection seg+      = line (pprCOFFComdatKey platform suffix <> colon)+      | otherwise+      = empty  -- | Output the ELF .size directive. pprSizeDecl :: IsDoc doc => Platform -> CLabel -> doc@@ -138,20 +148,26 @@       (l@LOCATION{} : _) -> pprInstr platform l       _other             -> empty -pprDatas :: IsDoc doc => Platform -> RawCmmStatics -> doc+pprDatas :: IsDoc doc => NCGConfig -> RawCmmStatics -> doc -- See Note [emit-time elimination of static indirections] in "GHC.Cmm.CLabel".-pprDatas platform (CmmStaticsRaw alias [CmmStaticLit (CmmLabel lbl), CmmStaticLit ind, _, _])+pprDatas config (CmmStaticsRaw alias [CmmStaticLit (CmmLabel lbl), CmmStaticLit ind, _, _])   | lbl == mkIndStaticInfoLabel   , let labelInd (CmmLabelOff l _) = Just l         labelInd (CmmLabel l) = Just l         labelInd _ = Nothing   , Just ind' <- labelInd ind   , alias `mayRedirectTo` ind'+  -- See Note [Split sections on COFF objects]+  , not $ platformOS platform == OSMinGW32 && ncgSplitSections config   = pprGloblDecl platform alias     $$ line (text ".equiv" <+> pprAsmLabel platform alias <> comma <> pprAsmLabel platform ind')+    where+      platform = ncgPlatform config -pprDatas platform (CmmStaticsRaw lbl dats)+pprDatas config (CmmStaticsRaw lbl dats)   = vcat (pprLabel platform lbl : map (pprData platform) dats)+    where+      platform = ncgPlatform config  pprData :: IsDoc doc => Platform -> CmmStatic -> doc pprData _platform (CmmString str) = line (pprString str)@@ -408,6 +424,7 @@   SXTB o1 o2       -> op2 (text "\tsxtb") o1 o2   UXTB o1 o2       -> op2 (text "\tuxtb") o1 o2   SXTH o1 o2       -> op2 (text "\tsxth") o1 o2+  SXTW o1 o2       -> op2 (text "\tsxtw") o1 o2   UXTH o1 o2       -> op2 (text "\tuxth") o1 o2    -- 3. Logical and Move Instructions ------------------------------------------@@ -455,12 +472,8 @@   -- NOTE: GHC may do whacky things where it only load the lower part of an   --       address. Not observing the correct size when loading will lead   --       inevitably to crashes.-  STR _f o1@(OpReg W8 (RegReal (RealRegSingle i))) o2 | i < 32 ->-    op2 (text "\tstrb") o1 o2-  STR _f o1@(OpReg W16 (RegReal (RealRegSingle i))) o2 | i < 32 ->-    op2 (text "\tstrh") o1 o2-  STR _f o1 o2 -> op2 (text "\tstr") o1 o2-  STLR _f o1 o2 -> op2 (text "\tstlr") o1 o2+  STR f o1 o2 ->  op2 (subword_suffix f $ text "\tstr") o1 o2+  STLR f o1 o2 -> op2 (subword_suffix f $ text "\tstlr") o1 o2    LDR _f o1 (OpImm (ImmIndex lbl' off)) | Just (_info, lbl) <- dynamicLinkerLabelInfo lbl' ->     let (adrp', ldr') = op_adrp_reloc_dynamic $ pprAsmLabel platform lbl in@@ -508,12 +521,8 @@     op_adrp o1 adrp' $$     op_add o1 ldr' -  LDR _f o1@(OpReg W8 (RegReal (RealRegSingle i))) o2 | i < 32 ->-    op2 (text "\tldrb") o1 o2-  LDR _f o1@(OpReg W16 (RegReal (RealRegSingle i))) o2 | i < 32 ->-    op2 (text "\tldrh") o1 o2-  LDR _f o1 o2 -> op2 (text "\tldr") o1 o2-  LDAR _f o1 o2 -> op2 (text "\tldar") o1 o2+  LDR f o1 o2 -> op2 (subword_suffix f $ text "\tldr") o1 o2+  LDAR f o1 o2 -> op2 (subword_suffix f $ text "\tldar") o1 o2    -- 8. Synchronization Instructions -------------------------------------------   DMBISH DmbLoadStore -> line $ text "\tdmb ish"@@ -556,6 +565,12 @@         check_off off = if off >= 0 && off <= 4095 then char '#' <> int off else          pgmError $ "GHC.CmmToAsm.AArch64.Ppr.check_off : " ++ show off ++ " is out of 12 bit"++       -- Some instructions encode subword ops via b/h suffix on the instruction.+       -- We handle this here relying on the format rather than the operands.+       subword_suffix II8  t = t <> char 'b'+       subword_suffix II16 t = t <> char 'h'+       subword_suffix _    t = t  pprBcond :: IsLine doc => Cond -> doc pprBcond c = text "b." <> pprCond c
GHC/CmmToAsm/PPC/CodeGen.hs view
@@ -182,7 +182,7 @@               format = cmmTypeFormat ty      CmmUnsafeForeignCall target result_regs args-       -> genCCall target result_regs args+       -> genCCall platform target result_regs args      CmmBranch id          -> genBranch id     CmmCondBranch arg true false prediction -> do@@ -340,6 +340,8 @@   let Reg64 hi lo = localReg64 local_reg   return (RegCode64 nilOL hi lo) +iselExpr64 regoff@(CmmRegOff _ _) = iselExpr64 $ mangleIndexTree regoff+ iselExpr64 (CmmLit (CmmInt i _)) = do   Reg64 rhi rlo <- getNewReg64   let@@ -469,48 +471,26 @@         return (Any II64 code)  -- catch simple cases of zero- or sign-extended load-getRegister' _ _ (CmmMachOp (MO_UU_Conv W8 W32) [CmmLoad mem _ _]) = do-    Amode addr addr_code <- getAmode D mem-    return (Any II32 (\dst -> addr_code `snocOL` LD II8 dst addr))--getRegister' _ _ (CmmMachOp (MO_XX_Conv W8 W32) [CmmLoad mem _ _]) = do-    Amode addr addr_code <- getAmode D mem-    return (Any II32 (\dst -> addr_code `snocOL` LD II8 dst addr))--getRegister' _ _ (CmmMachOp (MO_UU_Conv W8 W64) [CmmLoad mem _ _]) = do-    Amode addr addr_code <- getAmode D mem-    return (Any II64 (\dst -> addr_code `snocOL` LD II8 dst addr))--getRegister' _ _ (CmmMachOp (MO_XX_Conv W8 W64) [CmmLoad mem _ _]) = do-    Amode addr addr_code <- getAmode D mem-    return (Any II64 (\dst -> addr_code `snocOL` LD II8 dst addr))---- Note: there is no Load Byte Arithmetic instruction, so no signed case here--getRegister' _ _ (CmmMachOp (MO_UU_Conv W16 W32) [CmmLoad mem _ _]) = do-    Amode addr addr_code <- getAmode D mem-    return (Any II32 (\dst -> addr_code `snocOL` LD II16 dst addr))--getRegister' _ _ (CmmMachOp (MO_SS_Conv W16 W32) [CmmLoad mem _ _]) = do-    Amode addr addr_code <- getAmode D mem-    return (Any II32 (\dst -> addr_code `snocOL` LA II16 dst addr))--getRegister' _ _ (CmmMachOp (MO_UU_Conv W16 W64) [CmmLoad mem _ _]) = do-    Amode addr addr_code <- getAmode D mem-    return (Any II64 (\dst -> addr_code `snocOL` LD II16 dst addr))--getRegister' _ _ (CmmMachOp (MO_SS_Conv W16 W64) [CmmLoad mem _ _]) = do-    Amode addr addr_code <- getAmode D mem-    return (Any II64 (\dst -> addr_code `snocOL` LA II16 dst addr))+getRegister' _ _ (CmmMachOp (MO_UU_Conv src tgt) [CmmLoad mem pk _])+  | src < tgt+  , cmmTypeFormat pk == intFormat src = loadZeroExpand mem pk tgt -getRegister' _ _ (CmmMachOp (MO_UU_Conv W32 W64) [CmmLoad mem _ _]) = do-    Amode addr addr_code <- getAmode D mem-    return (Any II64 (\dst -> addr_code `snocOL` LD II32 dst addr))+getRegister' _ _ (CmmMachOp (MO_XX_Conv src tgt) [CmmLoad mem pk _])+  | src < tgt+  , cmmTypeFormat pk == intFormat src = loadZeroExpand mem pk tgt -getRegister' _ _ (CmmMachOp (MO_SS_Conv W32 W64) [CmmLoad mem _ _]) = do-    -- lwa is DS-form. See Note [Power instruction format]-    Amode addr addr_code <- getAmode DS mem-    return (Any II64 (\dst -> addr_code `snocOL` LA II32 dst addr))+  -- XXX: This is ugly, refactor+getRegister' _ _ (CmmMachOp (MO_SS_Conv src tgt) [CmmLoad mem pk _])+  -- Note: there is no Load Byte Arithmetic instruction+  | cmmTypeFormat pk /= II8+  , src < tgt = do+      let format = cmmTypeFormat pk+      -- lwa is DS-form. See Note [Power instruction format]+      let form = if format >= II32 then DS else D+      Amode addr addr_code <- getAmode form mem+      let code dst = assert (format == intFormat src)+                     $ addr_code `snocOL` LA format dst addr+      return (Any (intFormat tgt) code)  getRegister' config platform (CmmMachOp (MO_RelaxedRead w) [e]) =       getRegister' config platform (CmmLoad e (cmmBits w) NaturallyAligned)@@ -563,7 +543,7 @@                                  CLRLI arch_fmt dst src1 (arch_bits - size)                  return (Any (intFormat to) code) -getRegister' _ _ (CmmMachOp mop [x, y]) -- dyadic PrimOps+getRegister' _ platform (CmmMachOp mop [x, y]) -- dyadic PrimOps   = case mop of       MO_F_Eq _ -> condFltReg EQQ x y       MO_F_Ne _ -> condFltReg NE  x y@@ -646,8 +626,9 @@                 (src, srcCode) <- getSomeReg x                 let clear_mask = if imm == -4 then 2 else 3                     fmt = intFormat rep+                    arch_fmt = intFormat (wordWidth platform)                     code dst = srcCode-                               `appOL` unitOL (CLRRI fmt dst src clear_mask)+                      `appOL` unitOL (CLRRI arch_fmt dst src clear_mask)                 return (Any fmt code)         _ -> trivialCode rep False AND x y       MO_Or rep    -> trivialCode rep False OR x y@@ -791,6 +772,12 @@ extendUExpr :: Width -> Width -> CmmExpr -> CmmExpr extendUExpr from to x = CmmMachOp (MO_UU_Conv from to) [x] +loadZeroExpand :: CmmExpr -> CmmType -> Width -> NatM Register+loadZeroExpand mem pk tgt = do+    Amode addr addr_code <- getAmode D mem+    let code dst = addr_code `snocOL` LD (cmmTypeFormat pk) dst addr+    return (Any (intFormat tgt) code)+ -- ----------------------------------------------------------------------------- --  The 'Amode' type: Memory addressing modes passed up the tree. @@ -1200,24 +1187,25 @@ -- @get_arg@, which moves the arguments to the correct registers/stack -- locations.  Apart from that, the code is easy. -genCCall :: ForeignTarget      -- function to call+genCCall :: Platform+         -> ForeignTarget      -- function to call          -> [CmmFormal]        -- where to put the result          -> [CmmActual]        -- arguments (of mixed type)          -> NatM InstrBlock-genCCall (PrimTarget MO_AcquireFence) _ _+genCCall _ (PrimTarget MO_AcquireFence) _ _  = return $ unitOL LWSYNC-genCCall (PrimTarget MO_ReleaseFence) _ _+genCCall _ (PrimTarget MO_ReleaseFence) _ _  = return $ unitOL LWSYNC-genCCall (PrimTarget MO_SeqCstFence) _ _+genCCall _ (PrimTarget MO_SeqCstFence) _ _  = return $ unitOL HWSYNC -genCCall (PrimTarget MO_Touch) _ _+genCCall _ (PrimTarget MO_Touch) _ _  = return $ nilOL -genCCall (PrimTarget (MO_Prefetch_Data _)) _ _+genCCall _ (PrimTarget (MO_Prefetch_Data _)) _ _  = return $ nilOL -genCCall (PrimTarget (MO_AtomicRMW width amop)) [dst] [addr, n]+genCCall _ (PrimTarget (MO_AtomicRMW width amop)) [dst] [addr, n]  = do let fmt      = intFormat width           reg_dst  = getLocalRegReg dst       (instr, n_code) <- case amop of@@ -1267,7 +1255,7 @@                           (n_reg, n_code) <- getSomeReg n                           return  (op dst dst (RIReg n_reg), n_code) -genCCall (PrimTarget (MO_AtomicRead width _)) [dst] [addr]+genCCall _ (PrimTarget (MO_AtomicRead width _)) [dst] [addr]  = do let fmt      = intFormat width           reg_dst  = getLocalRegReg dst           form     = if widthInBits width == 64 then DS else D@@ -1294,12 +1282,12 @@ -- This is also what gcc does.  -genCCall (PrimTarget (MO_AtomicWrite width _)) [] [addr, val] = do+genCCall _ (PrimTarget (MO_AtomicWrite width _)) [] [addr, val] = do     code <- assignMem_IntCode (intFormat width) addr val     return $ unitOL HWSYNC `appOL` code -genCCall (PrimTarget (MO_Cmpxchg width)) [dst] [addr, old, new]-  | width == W32 || width == W64+genCCall platform (PrimTarget (MO_Cmpxchg width)) [dst] [addr, old, new]+  | width == W32 || (width == W64 && not (target32Bit platform))   = do       (old_reg, old_code) <- getSomeReg old       (new_reg, new_code) <- getSomeReg new@@ -1328,9 +1316,8 @@     format = intFormat width  -genCCall (PrimTarget (MO_Clz width)) [dst] [src]- = do platform <- getPlatform-      let reg_dst = getLocalRegReg dst+genCCall platform (PrimTarget (MO_Clz width)) [dst] [src]+ = do let reg_dst = getLocalRegReg dst       if target32Bit platform && width == W64         then do           RegCode64 code vr_hi vr_lo <- iselExpr64 src@@ -1378,9 +1365,8 @@           let cntlz = unitOL (CNTLZ format reg_dst reg)           return $ s_code `appOL` pre `appOL` cntlz `appOL` post -genCCall (PrimTarget (MO_Ctz width)) [dst] [src]- = do platform <- getPlatform-      let reg_dst = getLocalRegReg dst+genCCall platform (PrimTarget (MO_Ctz width)) [dst] [src]+ = do let reg_dst = getLocalRegReg dst       if target32Bit platform && width == W64         then do           let format = II32@@ -1442,9 +1428,8 @@                           , SUBFC dst r' (RIImm (ImmInt (format_bits)))                           ] -genCCall target dest_regs argsAndHints- = do platform <- getPlatform-      case target of+genCCall platform target dest_regs argsAndHints+ = do case target of         PrimTarget (MO_S_QuotRem  width) -> divOp1 True  width                                                    dest_regs argsAndHints         PrimTarget (MO_U_QuotRem  width) -> divOp1 False width@@ -2450,8 +2435,8 @@   let op_len = max W32 width       extend = if sgn then extendSExpr else extendUExpr   (src1, code1) <- getSomeReg (extend width op_len x)-  (src2, code2) <- getSomeReg (extendUExpr width op_len y)-  -- Note: Shift amount `y` is unsigned+  (src2, code2) <- getSomeReg y+   let code dst = code1 `appOL` code2 `snocOL`                  instr (intFormat op_len) dst src1 (RIReg src2)   return (Any (intFormat width) code)
GHC/CmmToAsm/Ppr.hs view
@@ -1,4 +1,5 @@ {-# LANGUAGE MagicHash #-}+{-# LANGUAGE MultiWayIf #-}  ----------------------------------------------------------------------------- --@@ -14,6 +15,7 @@         pprASCII,         pprString,         pprFileEmbed,+        pprCOFFComdatKey,         pprSectionHeader ) @@ -23,6 +25,7 @@  import GHC.Utils.Asm import GHC.Cmm.CLabel+import GHC.Cmm.InitFini import GHC.Cmm import GHC.CmmToAsm.Config import GHC.Utils.Outputable as SDoc@@ -220,8 +223,8 @@                     | otherwise -> text ".rodata"       RelocatableReadOnlyData | OSMinGW32 <- platformOS platform                                 -- Concept does not exist on Windows,-                                -- So map these to R/O data.-                                          -> text ".rdata$rel.ro"+                                -- So map these to data.+                                          -> text ".data"                               | otherwise -> text ".data.rel.ro"       UninitialisedData -> text ".bss"       InitArray@@ -238,19 +241,74 @@         | otherwise -> text ".rodata.str"       OtherSection _ ->         panic "PprBase.pprGNUSectionHeader: unknown section type"-    flags = case t of-      Text-        | OSMinGW32 <- platformOS platform, splitSections-                    -> text ",\"xr\""-        | splitSections-                    -> text ",\"ax\"," <> sectionType platform "progbits"-      CString-        | OSMinGW32 <- platformOS platform-                    -> empty-        | otherwise -> text ",\"aMS\"," <> sectionType platform "progbits" <> text ",1"-      _ -> empty+    flags+      -- See+      -- https://github.com/llvm/llvm-project/blob/llvmorg-21.1.8/lld/COFF/Chunks.cpp#L54+      -- and https://llvm.org/docs/Extensions.html#section-directive.+      -- LLD COFF backend gc-sections only work on COMDAT sections so+      -- we need to mark it as a COMDAT section. You can use clang64+      -- toolchain to compile small examples with+      -- `-ffunction-sections -fdata-sections -S` to see these section+      -- headers in the wild. Also see Note [Split sections on COFF objects]+      -- below.+      | OSMinGW32 <- platformOS platform,+        splitSections =+          if+            | Just _ <- isInitOrFiniSection t -> text ",\"dw\""+            | otherwise ->+                let coff_section_flags+                      | Text <- t = "xr"+                      | UninitialisedData <- t = "bw"+                      | ReadOnlySection <- sectionProtection t = "dr"+                      | otherwise = "dw"+                 in hcat+                      [ text ",\"",+                        text coff_section_flags,+                        text "\",one_only,",+                        pprCOFFComdatKey platform suffix+                      ]+      | otherwise =+          case t of+            Text+              | splitSections+                          -> text ",\"ax\"," <> sectionType platform "progbits"+            CString+              | OSMinGW32 <- platformOS platform+                          -> empty+              | otherwise -> text ",\"aMS\"," <> sectionType platform "progbits" <> text ",1"+            _ -> empty {-# SPECIALIZE pprGNUSectionHeader :: NCGConfig -> SectionType -> CLabel -> SDoc #-} {-# SPECIALIZE pprGNUSectionHeader :: NCGConfig -> SectionType -> CLabel -> HLine #-} -- see Note [SPECIALIZE to HDoc] in GHC.Utils.Outputable++-- | Note [Split sections on COFF objects]+-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+--+-- On Windows/COFF, LLD's gc-sections only works on COMDAT sections,+-- so we mark split sections as COMDAT and need to provide a unique+-- "key" symbol.+--+-- Important: We must not use a dot-prefixed local label (e.g.+-- @.L...@) as the COMDAT key symbol, because LLVM's COFF assembler+-- treats dot-prefixed COMDAT key symbols specially and forces them to+-- have value 0 (the beginning of the section). That breaks+-- @tablesNextToCode@, where the info label is intentionally placed+-- after the info table data (at a non-zero offset).+--+-- Therefore we generate a non-dot-prefixed key symbol derived from+-- the section suffix, and (see arch-specific 'pprSectionAlign') we+-- emit a label definition for it at the beginning of the section.+--+-- ctor/dtor sections are specially treated; they must be emitted as+-- regular data sections, otherwise LLD will drop them.+--+-- Note that we must not emit .equiv directives for COMDAT sections in+-- COFF objects, they seriously confuse LLD and we end up with access+-- violations at runtimes.+pprCOFFComdatKey :: IsLine doc => Platform -> CLabel -> doc+pprCOFFComdatKey platform suffix =+  text "__ghc_coff_comdat_" <> pprAsmLabel platform suffix+{-# SPECIALIZE pprCOFFComdatKey :: Platform -> CLabel -> SDoc #-}+{-# SPECIALIZE pprCOFFComdatKey :: Platform -> CLabel -> HLine #-} -- see Note [SPECIALIZE to HDoc] in GHC.Utils.Outputable  -- XCOFF doesn't support relocating label-differences, so we place all -- RO sections into .text[PR] sections
GHC/CmmToAsm/RV64/CodeGen.hs view
@@ -724,7 +724,7 @@               ( \dst ->                   code                     `appOL` code_x-                    `snocOL` annExpr expr (FCVT IntToFloat (OpReg to dst) (OpReg from reg_x)) -- (Signed ConVerT Float)+                    `snocOL` annExpr expr (FCVT IntToFloat (OpReg to dst) (OpReg from reg_x) Rne) -- (Signed ConVerT Float)               )         MO_SF_Round from to ->           pure@@ -732,7 +732,7 @@               (floatFormat to)               ( \dst ->                   code-                    `snocOL` annExpr expr (FCVT IntToFloat (OpReg to dst) (OpReg from reg)) -- (Signed ConVerT Float)+                    `snocOL` annExpr expr (FCVT IntToFloat (OpReg to dst) (OpReg from reg) Rne) -- (Signed ConVerT Float)               )         -- TODO: Can this case happen?         MO_FS_Truncate from to@@ -744,7 +744,7 @@                       code                         `snocOL`                         -- W32 is the smallest width to convert to. Decrease width afterwards.-                        annExpr expr (FCVT FloatToInt (OpReg W32 dst) (OpReg from reg))+                        annExpr expr (FCVT FloatToInt (OpReg W32 dst) (OpReg from reg) Rtz)                         `appOL` signExtendAdjustPrecission W32 to dst dst -- (float convert (-> zero) signed)                   )         MO_FS_Truncate from to ->@@ -753,7 +753,7 @@               (intFormat to)               ( \dst ->                   code-                    `snocOL` annExpr expr (FCVT FloatToInt (OpReg to dst) (OpReg from reg))+                    `snocOL` annExpr expr (FCVT FloatToInt (OpReg to dst) (OpReg from reg) Rtz)                     `appOL` truncateReg from to dst -- (float convert (-> zero) signed)               )         MO_UU_Conv from to@@ -775,9 +775,18 @@                     `appOL` truncateReg from to dst               )         MO_SS_Conv from to -> ss_conv from to reg code-        MO_FF_Conv from to -> return $ Any (floatFormat to) (\dst -> code `snocOL` annExpr e (FCVT FloatToFloat (OpReg to dst) (OpReg from reg)))+        MO_FF_Conv from to -> return $ Any (floatFormat to) (\dst -> code `snocOL` annExpr e (FCVT FloatToFloat (OpReg to dst) (OpReg from reg) Rne))         MO_WF_Bitcast w    -> return $ Any (floatFormat w)  (\dst -> code `snocOL` MOV (OpReg w dst) (OpReg w reg))-        MO_FW_Bitcast w    -> return $ Any (intFormat w)    (\dst -> code `snocOL` MOV (OpReg w dst) (OpReg w reg))+        MO_FW_Bitcast w ->+          return+            $ Any+              (intFormat w)+              ( \dst ->+                  code+                    `snocOL` MOV (OpReg w dst) (OpReg w reg)+                    -- FMV.X.W sign-extends the value, so truncate the result+                    `appOL` truncateReg W64 w dst+              )          -- Conversions         -- TODO: Duplication with MO_UU_Conv
GHC/CmmToAsm/RV64/Instr.hs view
@@ -106,7 +106,7 @@   LDR _ dst src -> usage (regOp src, regOp dst)   LDRU _ dst src -> usage (regOp src, regOp dst)   FENCE _ _ -> usage ([], [])-  FCVT _variant dst src -> usage (regOp src, regOp dst)+  FCVT _variant dst src _rm -> usage (regOp src, regOp dst)   FABS dst src -> usage (regOp src, regOp dst)   FMIN dst src1 src2 -> usage (regOp src1 ++ regOp src2, regOp dst)   FMAX dst src1 src2 -> usage (regOp src1 ++ regOp src2, regOp dst)@@ -165,6 +165,7 @@     ++ map regSingle [t3RegNo .. t6RegNo]     ++ map regSingle [ft0RegNo .. ft7RegNo]     ++ map regSingle [fa0RegNo .. fa7RegNo]+    ++ map regSingle [ft8RegNo .. ft11RegNo]  -- | Apply a given mapping to all the register references in this instruction. patchRegsOfInstr :: Instr -> (Reg -> Reg) -> Instr@@ -205,7 +206,7 @@   LDR f o1 o2 -> LDR f (patchOp o1) (patchOp o2)   LDRU f o1 o2 -> LDRU f (patchOp o1) (patchOp o2)   FENCE o1 o2 -> FENCE o1 o2-  FCVT variant o1 o2 -> FCVT variant (patchOp o1) (patchOp o2)+  FCVT variant o1 o2 rm -> FCVT variant (patchOp o1) (patchOp o2) rm   FABS o1 o2 -> FABS (patchOp o1) (patchOp o2)   FMIN o1 o2 o3 -> FMIN (patchOp o1) (patchOp o2) (patchOp o3)   FMAX o1 o2 o3 -> FMAX (patchOp o1) (patchOp o2) (patchOp o3)@@ -612,7 +613,7 @@     -- Memory barrier.     FENCE FenceType FenceType   | -- | Floating point conversion-    FCVT FcvtVariant Operand Operand+    FCVT FcvtVariant Operand Operand RoundingMode   | -- | Floating point ABSolute value     FABS Operand Operand @@ -635,6 +636,21 @@  -- | Variant of a floating point conversion instruction data FcvtVariant = FloatToFloat | IntToFloat | FloatToInt++-- | The rounding mode associated with an instruction+data RoundingMode+  = -- | Round to nearest, ties to even+    Rne+  | -- | Round toward zero+    Rtz+  | -- | Round downward (toward negative infinity)+    Rdn+  | -- | Round upward (toward positive infinity)+    Rup+  | -- | Round to nearest, ties to max magnitude+    Rmm+  | -- | Dynamic rounding mode+    Dyn  instrCon :: Instr -> String instrCon i =
GHC/CmmToAsm/RV64/Ppr.hs view
@@ -409,6 +409,17 @@       -- no support for widths > W64.       | otherwise = pprPanic "Unsupported width in register (max is 64)" (ppr w <+> int i) +-- | Pretty print a rounding mode+--+-- If the rounding mode is omitted, 'dyn' will be used.+pprRm :: IsLine doc => RoundingMode -> doc+pprRm Rne = text "rne"+pprRm Rtz = text "rtz"+pprRm Rdn = text "rdn"+pprRm Rup = text "rup"+pprRm Rmm = text "rmm"+pprRm Dyn = text "dyn"+ -- | Single precission `Operand` (floating-point) isSingleOp :: Operand -> Bool isSingleOp (OpReg W32 _) = True@@ -646,25 +657,26 @@   LDRU FF64 o1 o2@(OpAddr (AddrRegImm _ _)) -> op2 (text "\tfld") o1 o2   LDRU f o1 o2 -> pprPanic "Unsupported unsigned load" ((text . show) f <+> pprOp platform o1 <+> pprOp platform o2)   FENCE r w -> line $ text "\tfence" <+> pprFenceType r <> char ',' <+> pprFenceType w-  FCVT FloatToFloat o1@(OpReg W32 _) o2@(OpReg W64 _) -> op2 (text "\tfcvt.s.d") o1 o2-  FCVT FloatToFloat o1@(OpReg W64 _) o2@(OpReg W32 _) -> op2 (text "\tfcvt.d.s") o1 o2-  FCVT FloatToFloat o1 o2 ->+  FCVT FloatToFloat o1@(OpReg W32 _) o2@(OpReg W64 _) rm -> op2rm (text "\tfcvt.s.d") o1 o2 rm+  -- The assembler seems to be unhappy with explicit rounding mode on fcvt.d.s+  FCVT FloatToFloat o1@(OpReg W64 _) o2@(OpReg W32 _) _rm -> op2 (text "\tfcvt.d.s") o1 o2+  FCVT FloatToFloat o1 o2 rm ->     pprPanic "RV64.pprInstr - impossible float to float conversion"-      $ line (pprOp platform o1 <> text "->" <> pprOp platform o2)-  FCVT IntToFloat o1@(OpReg W32 _) o2@(OpReg W32 _) -> op2 (text "\tfcvt.s.w") o1 o2-  FCVT IntToFloat o1@(OpReg W32 _) o2@(OpReg W64 _) -> op2 (text "\tfcvt.s.l") o1 o2-  FCVT IntToFloat o1@(OpReg W64 _) o2@(OpReg W32 _) -> op2 (text "\tfcvt.d.w") o1 o2-  FCVT IntToFloat o1@(OpReg W64 _) o2@(OpReg W64 _) -> op2 (text "\tfcvt.d.l") o1 o2-  FCVT IntToFloat o1 o2 ->+      $ line (pprOp platform o1 <> text "->" <> pprOp platform o2 <> text "," <> pprRm rm)+  FCVT IntToFloat o1@(OpReg W32 _) o2@(OpReg W32 _) rm -> op2rm (text "\tfcvt.s.w") o1 o2 rm+  FCVT IntToFloat o1@(OpReg W32 _) o2@(OpReg W64 _) rm -> op2rm (text "\tfcvt.s.l") o1 o2 rm+  FCVT IntToFloat o1@(OpReg W64 _) o2@(OpReg W32 _) rm -> op2rm (text "\tfcvt.d.w") o1 o2 rm+  FCVT IntToFloat o1@(OpReg W64 _) o2@(OpReg W64 _) rm -> op2rm (text "\tfcvt.d.l") o1 o2 rm+  FCVT IntToFloat o1 o2 rm ->     pprPanic "RV64.pprInstr - impossible integer to float conversion"-      $ line (pprOp platform o1 <> text "->" <> pprOp platform o2)-  FCVT FloatToInt o1@(OpReg W32 _) o2@(OpReg W32 _) -> op2 (text "\tfcvt.w.s") o1 o2-  FCVT FloatToInt o1@(OpReg W32 _) o2@(OpReg W64 _) -> op2 (text "\tfcvt.w.d") o1 o2-  FCVT FloatToInt o1@(OpReg W64 _) o2@(OpReg W32 _) -> op2 (text "\tfcvt.l.s") o1 o2-  FCVT FloatToInt o1@(OpReg W64 _) o2@(OpReg W64 _) -> op2 (text "\tfcvt.l.d") o1 o2-  FCVT FloatToInt o1 o2 ->+      $ line (pprOp platform o1 <> text "->" <> pprOp platform o2 <> text "," <> pprRm rm)+  FCVT FloatToInt o1@(OpReg W32 _) o2@(OpReg W32 _) rm -> op2rm (text "\tfcvt.w.s") o1 o2 rm+  FCVT FloatToInt o1@(OpReg W32 _) o2@(OpReg W64 _) rm -> op2rm (text "\tfcvt.w.d") o1 o2 rm+  FCVT FloatToInt o1@(OpReg W64 _) o2@(OpReg W32 _) rm -> op2rm (text "\tfcvt.l.s") o1 o2 rm+  FCVT FloatToInt o1@(OpReg W64 _) o2@(OpReg W64 _) rm -> op2rm (text "\tfcvt.l.d") o1 o2 rm+  FCVT FloatToInt o1 o2 rm ->     pprPanic "RV64.pprInstr - impossible float to integer conversion"-      $ line (pprOp platform o1 <> text "->" <> pprOp platform o2)+      $ line (pprOp platform o1 <> text "->" <> pprOp platform o2 <> text "," <> pprRm rm)   FABS o1 o2 | isSingleOp o2 -> op2 (text "\tfabs.s") o1 o2   FABS o1 o2 | isDoubleOp o2 -> op2 (text "\tfabs.d") o1 o2   FMIN o1 o2 o3 | isSingleOp o1 -> op3 (text "\tfmin.s") o1 o2 o3@@ -681,6 +693,8 @@   instr -> panic $ "RV64.pprInstr - Unknown instruction: " ++ instrCon instr   where     op2 op o1 o2 = line $ op <+> pprOp platform o1 <> comma <+> pprOp platform o2+    op2rm op o1 o2 Dyn = line $ op <+> pprOp platform o1 <> comma <+> pprOp platform o2+    op2rm op o1 o2 rm = line $ op <+> pprOp platform o1 <> comma <+> pprOp platform o2 <> comma <+> pprRm rm     op3 op o1 o2 o3 = line $ op <+> pprOp platform o1 <> comma <+> pprOp platform o2 <> comma <+> pprOp platform o3     op4 op o1 o2 o3 o4 = line $ op <+> pprOp platform o1 <> comma <+> pprOp platform o2 <> comma <+> pprOp platform o3 <> comma <+> pprOp platform o4     pprFenceType FenceRead = text "r"
GHC/CmmToAsm/RV64/Regs.hs view
@@ -52,9 +52,14 @@ d7RegNo = 39 ft7RegNo = d7RegNo +d28RegNo, ft8RegNo :: RegNo+d28RegNo = 60+ft8RegNo = d28RegNo+ -- | Last floating point register.-d31RegNo :: RegNo+d31RegNo, ft11RegNo :: RegNo d31RegNo = 63+ft11RegNo = d31RegNo  a0RegNo, x10RegNo :: RegNo x10RegNo = 10
GHC/CmmToAsm/Reg/Graph.hs view
@@ -339,14 +339,14 @@ --   Conflicts between virtual and real regs are recorded as exclusions. graphAddConflictSet         :: Platform-        -> UniqSet RegWithFormat+        -> Regs         -> Color.Graph VirtualReg RegClass RealReg         -> Color.Graph VirtualReg RegClass RealReg  graphAddConflictSet platform regs graph  = let  arch = platformArch platform-        virtuals = takeVirtualRegs regs-        reals    = takeRealRegs regs+        virtuals = takeVirtualRegs $ getRegs regs+        reals    = takeRealRegs $ getRegs regs          graph1  = Color.addConflicts virtuals (classOfVirtualReg arch) graph           -- NB: we could add "arch" as argument to functions such as "addConflicts"
GHC/CmmToAsm/Reg/Graph/Coalesce.hs view
@@ -13,10 +13,8 @@ import GHC.Data.Bag import GHC.Data.Graph.Directed import GHC.Platform (Platform)-import GHC.Types.Unique (getUnique) import GHC.Types.Unique.FM import GHC.Types.Unique.Supply-import GHC.Types.Unique.Set  -- | Do register coalescing on this top level thing --@@ -88,8 +86,8 @@         slurpLI    rs (LiveInstr _      Nothing)    = rs         slurpLI    rs (LiveInstr instr (Just live))                 | Just (r1, r2) <- takeRegRegMoveInstr platform instr-                , elemUniqSet_Directly (getUnique r1) $ liveDieRead live-                , elemUniqSet_Directly (getUnique r2) $ liveBorn live+                , r1 `elemRegs` liveDieRead live+                , r2 `elemRegs` liveBorn live                  -- only coalesce movs between two virtuals for now,                 -- else we end up with allocatable regs in the live
GHC/CmmToAsm/Reg/Graph/Spill.hs view
@@ -144,7 +144,7 @@         -- then record the fact that these slots are now live in those blocks         -- in the given slotmap.         patchLiveSlot-                :: BlockMap IntSet -> BlockId -> UniqSet RegWithFormat-> BlockMap IntSet+                :: BlockMap IntSet -> BlockId -> Regs -> BlockMap IntSet          patchLiveSlot slotMap blockId regsLive          = let@@ -154,7 +154,8 @@                  moreSlotsLive   = IntSet.fromList                                 $ mapMaybe (lookupUFM regSlotMap . regWithFormat_reg)-                                $ nonDetEltsUniqSet regsLive+                                $ nonDetEltsUniqSet+                                $ getRegs regsLive                     -- See Note [Unique Determinism and code generation]                  slotMap'
GHC/CmmToAsm/Reg/Graph/SpillCost.hs view
@@ -102,7 +102,7 @@         countBlock info freqMap (BasicBlock blockId instrs)                 | LiveInfo _ _ blockLive _ <- info                 , Just rsLiveEntry  <- mapLookup blockId blockLive-                , rsLiveEntry_virt  <- takeVirtualRegs rsLiveEntry+                , rsLiveEntry_virt  <- takeVirtualRegs $ getRegs rsLiveEntry                 = countLIs (ceiling $ blockFreq freqMap blockId) rsLiveEntry_virt instrs                  | otherwise@@ -136,9 +136,9 @@                 mapM_ (incDefs scale) $ nub $ mapMaybe (takeVirtualReg . regWithFormat_reg) written                  -- Compute liveness for entry to next instruction.-                let liveDieRead_virt    = takeVirtualRegs (liveDieRead  live)-                let liveDieWrite_virt   = takeVirtualRegs (liveDieWrite live)-                let liveBorn_virt       = takeVirtualRegs (liveBorn     live)+                let liveDieRead_virt    = takeVirtualRegs $ getRegs (liveDieRead  live)+                let liveDieWrite_virt   = takeVirtualRegs $ getRegs (liveDieWrite live)+                let liveBorn_virt       = takeVirtualRegs $ getRegs (liveBorn     live)                  let rsLiveAcross                         = rsLiveEntry `minusUniqSet` liveDieRead_virt
GHC/CmmToAsm/Reg/Linear.hs view
@@ -207,7 +207,7 @@         :: forall instr. (Instruction instr)         => NCGConfig         -> [BlockId] -- ^ entry points-        -> BlockMap (UniqSet RegWithFormat)+        -> BlockMap Regs               -- ^ live regs on entry to each basic block         -> [SCC (LiveBasicBlock instr)]               -- ^ instructions annotated with "deaths"@@ -246,7 +246,7 @@         => NCGConfig         -> freeRegs         -> [BlockId]                    -- ^ entry points-        -> BlockMap (UniqSet RegWithFormat)              -- ^ live regs on entry to each basic block+        -> BlockMap Regs              -- ^ live regs on entry to each basic block         -> [SCC (LiveBasicBlock instr)] -- ^ instructions annotated with "deaths"         -> UniqDSM ([NatBasicBlock instr], RegAllocStats, Int) @@ -260,7 +260,7 @@  linearRA_SCCs :: OutputableRegConstraint freeRegs instr               => [BlockId]-              -> BlockMap (UniqSet RegWithFormat)+              -> BlockMap Regs               -> [NatBasicBlock instr]               -> [SCC (LiveBasicBlock instr)]               -> RegM freeRegs [NatBasicBlock instr]@@ -295,7 +295,7 @@  process :: forall freeRegs instr. (OutputableRegConstraint freeRegs instr)         => [BlockId]-        -> BlockMap (UniqSet RegWithFormat)+        -> BlockMap Regs         -> [GenBasicBlock (LiveInstr instr)]         -> RegM freeRegs [[NatBasicBlock instr]] process entry_ids block_live =@@ -334,7 +334,7 @@ -- processBlock         :: OutputableRegConstraint freeRegs instr-        => BlockMap (UniqSet RegWithFormat)              -- ^ live regs on entry to each basic block+        => BlockMap Regs              -- ^ live regs on entry to each basic block         -> LiveBasicBlock instr         -- ^ block to do register allocation on         -> RegM freeRegs [NatBasicBlock instr]   -- ^ block with registers allocated @@ -351,7 +351,7 @@ -- | Load the freeregs and current reg assignment into the RegM state --      for the basic block with this BlockId. initBlock :: FR freeRegs-          => BlockId -> BlockMap (UniqSet RegWithFormat) -> RegM freeRegs ()+          => BlockId -> BlockMap Regs -> RegM freeRegs () initBlock id block_live  = do   platform    <- getPlatform         block_assig <- getBlockAssigR@@ -368,7 +368,7 @@                             setFreeRegsR    (frInitFreeRegs platform)                           Just live ->                             setFreeRegsR $ foldl' (flip $ frAllocateReg platform) (frInitFreeRegs platform)-                                                  (nonDetEltsUniqSet $ takeRealRegs live)+                                                  (nonDetEltsUniqSet $ takeRealRegs $ getRegs live)                             -- See Note [Unique Determinism and code generation]                         setAssigR       emptyRegMap @@ -381,7 +381,7 @@ -- | Do allocation for a sequence of instructions. linearRA         :: forall freeRegs instr. (OutputableRegConstraint freeRegs instr)-        => BlockMap (UniqSet RegWithFormat)                      -- ^ map of what vregs are live on entry to each block.+        => BlockMap Regs                      -- ^ map of what vregs are live on entry to each block.         -> BlockId                              -- ^ id of the current block, for debugging.         -> [LiveInstr instr]                    -- ^ liveness annotated instructions in this block.         -> RegM freeRegs@@ -406,7 +406,7 @@ -- | Do allocation for a single instruction. raInsn         :: OutputableRegConstraint freeRegs instr-        => BlockMap (UniqSet RegWithFormat)                      -- ^ map of what vregs are love on entry to each block.+        => BlockMap Regs                         -- ^ map of what vregs are live on entry to each block.         -> [instr]                              -- ^ accumulator for instructions already processed.         -> BlockId                              -- ^ the id of the current block, for debugging         -> LiveInstr instr                      -- ^ the instr to have its regs allocated, with liveness info.@@ -427,7 +427,7 @@ raInsn block_live new_instrs id (LiveInstr (Instr instr) (Just live))  = do     platform <- getPlatform-    assig    <- getAssigR :: RegM freeRegs (UniqFM Reg Loc)+    assig    <- getAssigR      -- If we have a reg->reg move between virtual registers, where the     -- src register is not live after this instruction, and the dst@@ -437,12 +437,12 @@     -- (we can't eliminate it if the source register is on the stack, because     --  we do not want to use one spill slot for different virtual registers)     case takeRegRegMoveInstr platform instr of-        Just (src,dst)  | Just (RegWithFormat _ fmt) <- lookupUniqSet_Directly (liveDieRead live) (getUnique src),+        Just (src,dst)  | Just fmt <- lookupReg src (liveDieRead live),                           isVirtualReg dst,                           not (dst `elemUFM` assig),                           isRealReg src || isInReg src assig -> do            case src of-              RegReal rr -> setAssigR (addToUFM assig dst (InReg $ RealRegUsage rr fmt))+              RegReal rr -> setAssigR (addToUFM assig dst (Loc (InReg rr) fmt))                 -- if src is a fixed reg, then we just map dest to this                 -- reg in the assignment.  src must be an allocatable reg,                 -- otherwise it wouldn't be in r_dying.@@ -461,8 +461,8 @@            return (new_instrs, [])          _ -> genRaInsn block_live new_instrs id instr-                        (map regWithFormat_reg $ nonDetEltsUniqSet $ liveDieRead live)-                        (map regWithFormat_reg $ nonDetEltsUniqSet $ liveDieWrite live)+                        (map regWithFormat_reg $ nonDetEltsUniqSet $ getRegs $ liveDieRead live)+                        (map regWithFormat_reg $ nonDetEltsUniqSet $ getRegs $ liveDieWrite live)                         -- See Note [Unique Determinism and code generation]  raInsn _ _ _ instr@@ -485,13 +485,16 @@   isInReg :: Reg -> RegMap Loc -> Bool-isInReg src assig | Just (InReg _) <- lookupUFM assig src = True-                  | otherwise = False+isInReg src assig+  | Just (Loc (InReg _) _) <- lookupUFM assig src+  = True+  | otherwise+  = False   genRaInsn :: forall freeRegs instr.              (OutputableRegConstraint freeRegs instr)-          => BlockMap (UniqSet RegWithFormat)+          => BlockMap Regs           -> [instr]           -> BlockId           -> instr@@ -504,8 +507,8 @@   platform <- getPlatform   case regUsageOfInstr platform instr of { RU read written ->     do-    let real_written = [ rr                      | RegWithFormat {regWithFormat_reg = RegReal rr} <- written ]-    let virt_written = [ VirtualRegWithFormat vr fmt | RegWithFormat (RegVirtual vr) fmt         <- written ]+    let real_written = [ rr                          | RegWithFormat {regWithFormat_reg = RegReal rr} <- written ]+    let virt_written = [ VirtualRegWithFormat vr fmt | RegWithFormat (RegVirtual vr) fmt              <- written ]      -- we don't need to do anything with real registers that are     -- only read by this instr.  (the list is typically ~2 elements,@@ -643,14 +646,16 @@       loop assig !free (RegReal rr : rs) = loop assig (frReleaseReg platform rr free) rs       loop assig !free (r:rs) =          case lookupUFM assig r of-         Just (InBoth real _) -> loop (delFromUFM assig r)-                                      (frReleaseReg platform (realReg real) free) rs-         Just (InReg real)    -> loop (delFromUFM assig r)-                                      (frReleaseReg platform (realReg real) free) rs-         _                    -> loop (delFromUFM assig r) free rs+         Just (Loc (InBoth real _) _) ->+           loop (delFromUFM assig r)+                (frReleaseReg platform real free) rs+         Just (Loc (InReg real) _) ->+           loop (delFromUFM assig r)+                (frReleaseReg platform real free) rs+         _ ->+           loop (delFromUFM assig r) free rs   loop assig free regs - -- ----------------------------------------------------------------------------- -- Clobber real registers @@ -668,17 +673,18 @@ saveClobberedTemps         :: forall instr freeRegs.            (Instruction instr, FR freeRegs)-        => [RealReg]            -- real registers clobbered by this instruction-        -> [Reg]                -- registers which are no longer live after this insn-        -> RegM freeRegs [instr]         -- return: instructions to spill any temps that will-                                -- be clobbered.+        => [RealReg]             -- ^ real registers clobbered by this instruction+        -> [Reg]                 -- ^ registers which are no longer live after this instruction,+                                 -- because read for the last time+        -> RegM freeRegs [instr] -- return: instructions to spill any temps that will+                                 -- be clobbered.  saveClobberedTemps [] _         = return []  saveClobberedTemps clobbered dying  = do-        assig   <- getAssigR :: RegM freeRegs (UniqFM Reg Loc)+        assig   <- getAssigR         (assig',instrs) <- nonDetStrictFoldUFM_DirectlyM maybe_spill (assig,[]) assig         setAssigR assig'         return $ -- mkComment (text "<saveClobberedTemps>") ++@@ -687,19 +693,21 @@    where      -- Unique represents the VirtualReg      -- Here we separate the cases which we do want to spill from these we don't.-     maybe_spill :: Unique -> (RegMap Loc,[instr]) -> (Loc) -> RegM freeRegs (RegMap Loc,[instr])+     maybe_spill :: Unique+                 -> (RegMap Loc,[instr])+                 -> Loc+                 -> RegM freeRegs (RegMap Loc,[instr])      maybe_spill !temp !(assig,instrs) !loc =         case loc of                 -- This is non-deterministic but we do not                 -- currently support deterministic code-generation.                 -- See Note [Unique Determinism and code generation]-                InReg reg-                    | any (realRegsAlias $ realReg reg) clobbered+                Loc (InReg reg) fmt+                    | any (realRegsAlias reg) clobbered                     , temp `notElem` map getUnique dying-                    -> clobber temp (assig,instrs) reg+                    -> clobber temp (assig,instrs) (RealRegUsage reg fmt)                 _ -> return (assig,instrs) -      -- See Note [UniqFM and the register allocator]      clobber :: Unique -> (RegMap Loc,[instr]) -> RealRegUsage -> RegM freeRegs (RegMap Loc,[instr])      clobber temp (assig,instrs) (RealRegUsage reg fmt)@@ -718,7 +726,7 @@               (my_reg : _) -> do                   setFreeRegsR (frAllocateReg platform my_reg freeRegs) -                  let new_assign = addToUFM_Directly assig temp (InReg (RealRegUsage my_reg fmt))+                  let new_assign = addToUFM_Directly assig temp (Loc (InReg my_reg) fmt)                   let instr = mkRegRegMoveInstr config fmt                                   (RegReal reg) (RegReal my_reg) @@ -726,12 +734,13 @@                -- (2) no free registers: spill the value               [] -> do+                   (spill, slot)   <- spillR (RegWithFormat (RegReal reg) fmt) temp                    -- record why this reg was spilled for profiling                   recordSpill (SpillClobber temp) -                  let new_assign  = addToUFM_Directly assig temp (InBoth (RealRegUsage reg fmt) slot)+                  let new_assign  = addToUFM_Directly assig temp (Loc (InBoth reg slot) fmt)                    return (new_assign, (spill ++ instrs)) @@ -779,9 +788,9 @@         clobber assig []                 = assig -        clobber assig ((temp, InBoth reg slot) : rest)-                | any (realRegsAlias $ realReg reg) clobbered-                = clobber (addToUFM_Directly assig temp (InMem slot)) rest+        clobber assig ((temp, Loc (InBoth reg slot) regFmt) : rest)+                | any (realRegsAlias reg) clobbered+                = clobber (addToUFM_Directly assig temp (Loc (InMem slot) regFmt)) rest          clobber assig (_:rest)                 = clobber assig rest@@ -790,9 +799,9 @@ -- allocateRegsAndSpill  -- Why are we performing a spill?-data SpillLoc = ReadMem StackSlot  -- reading from register only in memory-              | WriteNew           -- writing to a new variable-              | WriteMem           -- writing to register only in memory+data SpillLoc = ReadMem StackSlot Format -- reading from register only in memory+              | WriteNew                 -- writing to a new variable+              | WriteMem                 -- writing to register only in memory -- Note that ReadNew is not valid, since you don't want to be reading -- from an uninitialized register.  We also don't need the location of -- the register in memory, since that will be invalidated by the write.@@ -818,28 +827,36 @@ allocateRegsAndSpill _       _    spills alloc []         = return (spills, reverse alloc) -allocateRegsAndSpill reading keep spills alloc (r@(VirtualRegWithFormat vr _fmt):rs)+allocateRegsAndSpill reading keep spills alloc (r@(VirtualRegWithFormat vr vrFmt):rs)  = do   assig <- toVRegMap <$> getAssigR         -- pprTraceM "allocateRegsAndSpill:assig" (ppr (r:rs) $$ ppr assig)         -- See Note [UniqFM and the register allocator]         let doSpill = allocRegsAndSpill_spill reading keep spills alloc r rs assig         case lookupUFM assig vr of                 -- case (1a): already in a register-                Just (InReg my_reg) ->-                        allocateRegsAndSpill reading keep spills (realReg my_reg:alloc) rs+                Just (Loc (InReg my_reg) in_reg_fmt) -> do+                  -- (RF1) from Note [Allocated register formats]:+                  -- writes redefine the format the register is used at.+                  when (not reading && vrFmt /= in_reg_fmt) $+                    setAssigR $ toRegMap $+                      addToUFM assig vr (Loc (InReg my_reg) vrFmt)+                  allocateRegsAndSpill reading keep spills (my_reg:alloc) rs                  -- case (1b): already in a register (and memory)-                -- NB1. if we're writing this register, update its assignment to be-                -- InReg, because the memory value is no longer valid.-                -- NB2. This is why we must process written registers here, even if they-                -- are also read by the same instruction.-                Just (InBoth my_reg _)-                 -> do  when (not reading) (setAssigR $ toRegMap (addToUFM assig vr (InReg my_reg)))-                        allocateRegsAndSpill reading keep spills (realReg my_reg:alloc) rs+                Just (Loc (InBoth my_reg _) _) -> do+                  -- NB1. if we're writing this register, update its assignment to be+                  -- InReg, because the memory value is no longer valid.+                  -- NB2. This is why we must process written registers here, even if they+                  -- are also read by the same instruction.+                  when (not reading) $+                    setAssigR $ toRegMap $+                      addToUFM assig vr (Loc (InReg my_reg) vrFmt)+                  allocateRegsAndSpill reading keep spills (my_reg:alloc) rs                  -- Not already in a register, so we need to find a free one...-                Just (InMem slot) | reading   -> doSpill (ReadMem slot)-                                  | otherwise -> doSpill WriteMem+                Just (Loc (InMem slot) memFmt)+                   | reading   -> doSpill (ReadMem slot memFmt)+                   | otherwise -> doSpill WriteMem                 Nothing | reading   ->                    pprPanic "allocateRegsAndSpill: Cannot read from uninitialized register" (ppr vr)                    -- NOTE: if the input to the NCG contains some@@ -875,7 +892,7 @@                         -> UniqFM VirtualReg Loc                         -> SpillLoc                         -> RegM freeRegs ([instr], [RealReg])-allocRegsAndSpill_spill reading keep spills alloc r@(VirtualRegWithFormat vr fmt) rs assig spill_loc+allocRegsAndSpill_spill reading keep spills alloc r@(VirtualRegWithFormat vr vrFmt) rs assig spill_loc  = do   platform <- getPlatform         freeRegs <- getFreeRegsR         let regclass = classOfVirtualReg (platformArch platform) vr@@ -897,7 +914,7 @@                 spills'   <- loadTemp r spill_loc final_reg spills                  setAssigR $ toRegMap-                          $ (addToUFM assig vr $! newLocation spill_loc $ RealRegUsage final_reg fmt)+                          $ (addToUFM assig vr $! newLocation spill_loc $ RealRegUsage final_reg vrFmt)                 setFreeRegsR $  frAllocateReg platform final_reg freeRegs                  allocateRegsAndSpill reading keep spills' (final_reg : alloc) rs@@ -911,7 +928,7 @@                 let candidates' :: UniqFM VirtualReg Loc                     candidates' =                       flip delListFromUFM (fmap virtualRegWithFormat_reg keep) $-                      filterUFM inRegOrBoth $+                      filterUFM (inRegOrBoth . locWithFormat_loc) $                       assig                       -- This is non-deterministic but we do not                       -- currently support deterministic code-generation.@@ -924,50 +941,54 @@                       == regclass                     candidates_inBoth :: [(Unique, RealRegUsage, StackSlot)]                     candidates_inBoth-                        = [ (temp, reg, mem)-                          | (temp, InBoth reg mem) <- candidates-                          , compat (realReg reg) ]+                        = [ (temp, RealRegUsage reg fmt, mem)+                          | (temp, Loc (InBoth reg mem) fmt) <- candidates+                          , compat reg ]                  -- the vregs we could kick out that are only in a reg                 --      this would require writing the reg to a new slot before using it.                 let candidates_inReg-                        = [ (temp, reg)-                          | (temp, InReg reg) <- candidates-                          , compat (realReg reg) ]+                        = [ (temp, RealRegUsage reg fmt)+                          | (temp, Loc (InReg reg) fmt) <- candidates+                          , compat reg ]                  let result                          -- we have a temporary that is in both register and mem,                         -- just free up its register for use.-                        | (temp, (RealRegUsage my_reg _old_fmt), slot) : _ <- candidates_inBoth-                        = do    spills' <- loadTemp r spill_loc my_reg spills-                                let assig1  = addToUFM_Directly assig temp (InMem slot)-                                let assig2  = addToUFM assig1 vr $! newLocation spill_loc (RealRegUsage my_reg fmt)+                        | (temp, (RealRegUsage cand_reg old_fmt), slot) : _ <- candidates_inBoth+                        = do    spills' <- loadTemp r spill_loc cand_reg spills+                                let assig1  = addToUFM_Directly assig temp $ Loc (InMem slot) old_fmt+                                let assig2  = addToUFM assig1 vr $! newLocation spill_loc (RealRegUsage cand_reg vrFmt)                                  setAssigR $ toRegMap assig2-                                allocateRegsAndSpill reading keep spills' (my_reg:alloc) rs+                                allocateRegsAndSpill reading keep spills' (cand_reg:alloc) rs                          -- otherwise, we need to spill a temporary that currently                         -- resides in a register.-                        | (temp_to_push_out, RealRegUsage my_reg fmt) : _+                        | (temp_to_push_out, RealRegUsage cand_reg old_reg_fmt) : _                                         <- candidates_inReg                         = do-                                (spill_store, slot) <- spillR (RegWithFormat (RegReal my_reg) fmt) temp_to_push_out+                                -- Spill what's currently in the register, with the format of what's in the register.+                                (spill_store, slot) <- spillR (RegWithFormat (RegReal cand_reg) old_reg_fmt) temp_to_push_out                                  -- record that this temp was spilled                                 recordSpill (SpillAlloc temp_to_push_out) -                                -- update the register assignment-                                let assig1  = addToUFM_Directly assig temp_to_push_out (InMem slot)-                                let assig2  = addToUFM assig1 vr $! newLocation spill_loc (RealRegUsage my_reg fmt)+                                -- Update the register assignment:+                                --  - the old data is now only in memory,+                                --  - the new data is now allocated to this register;+                                --    make sure to use the new format (#26542)+                                let assig1  = addToUFM_Directly assig temp_to_push_out $ Loc (InMem slot) old_reg_fmt+                                let assig2  = addToUFM assig1 vr $! newLocation spill_loc (RealRegUsage cand_reg vrFmt)                                 setAssigR $ toRegMap assig2                                  -- if need be, load up a spilled temp into the reg we've just freed up.-                                spills' <- loadTemp r spill_loc my_reg spills+                                spills' <- loadTemp r spill_loc cand_reg spills                                  allocateRegsAndSpill reading keep                                         (spill_store ++ spills')-                                        (my_reg:alloc) rs+                                        (cand_reg:alloc) rs                           -- there wasn't anything to spill, so we're screwed.@@ -976,7 +997,7 @@                         $ vcat                                 [ text "allocating vreg:  " <> text (show vr)                                 , text "assignment:       " <> ppr assig-                                , text "format:           " <> ppr fmt+                                , text "format:           " <> ppr vrFmt                                 , text "freeRegs:         " <> text (showRegs freeRegs)                                 , text "initFreeRegs:     " <> text (showRegs (frInitFreeRegs platform `asTypeOf` freeRegs))                                 ]@@ -988,9 +1009,12 @@ -- | Calculate a new location after a register has been loaded. newLocation :: SpillLoc -> RealRegUsage -> Loc -- if the tmp was read from a slot, then now its in a reg as well-newLocation (ReadMem slot) my_reg = InBoth my_reg slot+newLocation (ReadMem slot memFmt) (RealRegUsage r _regFmt) =+  -- See Note [Use spilled format when reloading]+  Loc (InBoth r slot) memFmt+ -- writes will always result in only the register being available-newLocation _ my_reg = InReg my_reg+newLocation _ (RealRegUsage r regFmt) = Loc (InReg r) regFmt  -- | Load up a spilled temporary if we need to (read from memory). loadTemp@@ -1001,11 +1025,91 @@         -> [instr]         -> RegM freeRegs [instr] -loadTemp (VirtualRegWithFormat vreg fmt) (ReadMem slot) hreg spills+loadTemp (VirtualRegWithFormat vreg _fmt) (ReadMem slot memFmt) hreg spills  = do-        insn <- loadR (RegWithFormat (RegReal hreg) fmt) slot+        -- See Note [Use spilled format when reloading]+        insn <- loadR (RegWithFormat (RegReal hreg) memFmt) slot         recordSpill (SpillLoad $ getUnique vreg)         return  $  {- mkComment (text "spill load") : -} insn ++ spills  loadTemp _ _ _ spills =    return spills++{- Note [Allocated register formats]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+We uphold the following principle for the format at which we keep track of+alllocated registers:++  RF1. Writes redefine the format.++    When we write to a register 'r' at format 'fmt', we consider the register+    to hold that format going forwards.++    (In cases where a partial write is desired, the move instruction should+     specify that the destination format is the full register, even if, say,+     the instruction only writes to the low 64 bits of the register.+     See also Wrinkle [Don't allow scalar partial writes] in+     Note [Register formats in liveness analysis] in GHC.CmmToAsm.Reg.Liveness.)++  RF2. Reads from a register do not redefine its format.++    Generally speaking, as explained in Note [Register formats in liveness analysis]+    in GHC.CmmToAsm.Reg.Liveness, when computing the used format from a collection+    of reads, we take a least upper bound.++It is particularly important to get (RF1) correct, as otherwise we can end up in+the situation of T26411b, where code such as++  movsd .Ln6m(%rip),%v1+  shufpd $0,%v1,%v1++we start off with %v1 :: F64, but after shufpd (which broadcasts the low part+to the high part) we must consider that %v1 :: F64x2. If we fail to do that,+then we will silently discard the top bits in spill/reload operations.+-}++{- Note [Use spilled format when reloading]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+We always reload at the full format that a register was spilled at. The rationale+is as follows:++  1. If later instructions only need the lower 64 bits of an XMM register,+     then we should have only spilled the lower 64 bits in the first place.+     (Whether this is true currently is another question.)+  2. If later instructions need say 128 bits, then we should immediately load+     the entire 128 bits, as this avoids multiple load instructions.++For (2), consider the situation of #26526, where we need to spill around a C+call (because we are using the System V ABI with no callee saved XMM registers).+Before register allocation, we have:++  vmovupd %v1 %v0+  call ...+  movsd   %v0 %v3+  movhlps %v0 %v4++The contents of %v0 need to be preserved across the call. We must spill %v0 at+format F64x2 (as later instructions need the entire 128 bits), and reload it+later. We thus expect something like:++  vmovupd %xmm1    %xmm0+  vmovupd %xmm0    72(%rsp) -- spill to preserve+  call ...+  vmovupd 72(%rsp) %xmm0    -- restore+  movsd   %xmm0    %xmm3+  movhlps %xmm0    %xmm4++This is certainly better than doing two loads from the stack, e.g.++  call ...+  movsd   72(%rsp) %xmm0 -- restore only lower 64 bits+  movsd   %xmm0    %xmm3+  vmovupd 72(%rsp) %xmm0 -- restore the full 128 bits+  movhlps %xmm0    %xmm4++The latter being especially risky because we don't want to believe %v0 is 'InBoth'+with format F64. The risk is that, when allocating registers for the 'VMOVUPD'+instruction, we think our data is already in a register and thus doesn't need to+be reloaded from memory, when in fact we have only loaded the lower 64 bits of+the data.+-}
GHC/CmmToAsm/Reg/Linear/Base.hs view
@@ -1,3 +1,4 @@+{-# LANGUAGE LambdaCase #-} {-# LANGUAGE RecordWildCards #-}  -- | Put common type definitions here to break recursive module dependencies.@@ -9,7 +10,7 @@         emptyBlockAssignment,         updateBlockAssignment, -        Loc(..),+        VLoc(..), Loc(..), IgnoreFormat(..),         regsOfLoc,         RealRegUsage(..), @@ -39,8 +40,6 @@ import GHC.CmmToAsm.Reg.Utils import GHC.CmmToAsm.Format -import Data.Function ( on )- data ReadingOrWriting = Reading | Writing deriving (Eq,Ord)  -- | Used to store the register assignment on entry to a basic block.@@ -70,8 +69,13 @@   -> BlockAssignment freeRegs   -> BlockAssignment freeRegs updateBlockAssignment dest (freeRegs, regMap) (BlockAssignment {..}) =-  BlockAssignment (mapInsert dest (freeRegs, regMap) blockMap)-                  (mergeUFM combWithExisting id (mapMaybeUFM fromLoc) (firstUsed) (toVRegMap regMap))+  BlockAssignment+    (mapInsert dest (freeRegs, regMap) blockMap)+    (mergeUFM combWithExisting id+        (mapMaybeUFM (fromVLoc . locWithFormat_loc))+        firstUsed+        (toVRegMap regMap)+    )   where     -- The blocks are processed in dependency order, so if there's already an     -- entry in the map then keep that assignment rather than writing the new@@ -79,13 +83,14 @@     combWithExisting :: RealReg -> Loc -> Maybe RealReg     combWithExisting old_reg _ = Just $ old_reg -    fromLoc :: Loc -> Maybe RealReg-    fromLoc (InReg rr) = Just $ realReg rr-    fromLoc (InBoth rr _) = Just $ realReg rr-    fromLoc _ = Nothing-+    fromVLoc :: VLoc -> Maybe RealReg+    fromVLoc (InReg rr) = Just rr+    fromVLoc (InBoth rr _) = Just rr+    fromVLoc _ = Nothing --- | Where a vreg is currently stored+-- | Where a vreg is currently stored.+--+-- --      A temporary can be marked as living in both a register and memory --      (InBoth), for example if it was recently loaded from a spill location. --      This makes it cheap to spill (no save instruction required), but we@@ -96,22 +101,41 @@ --      save it in a spill location, but mark it as InBoth because the current --      instruction might still want to read it. ---data Loc+data VLoc         -- | vreg is in a register-        = InReg   {-# UNPACK #-} !RealRegUsage+        = InReg   {-# UNPACK #-} !RealReg          -- | vreg is held in stack slots-        | InMem   {-# UNPACK #-}  !StackSlot-+        | InMem   {-# UNPACK #-} !StackSlot          -- | vreg is held in both a register and stack slots-        | InBoth   {-# UNPACK #-} !RealRegUsage-                   {-# UNPACK #-} !StackSlot+        | InBoth  {-# UNPACK #-} !RealReg+                  {-# UNPACK #-} !StackSlot         deriving (Eq, Ord, Show) -instance Outputable Loc where+-- | Where a virtual register is stored, together with the format it is stored at.+--+-- See 'VLoc'.+data Loc+  = Loc+  { locWithFormat_loc    :: {-# UNPACK #-} !VLoc+  , locWithFormat_format :: Format+  }++-- | A newtype used to hang off 'Eq' and 'Ord' instances for 'Loc' which+-- ignore the format, as used in 'GHC.CmmToAsm.Reg.Linear.JoinToTargets'.+newtype IgnoreFormat a = IgnoreFormat a+instance Eq (IgnoreFormat Loc) where+  IgnoreFormat (Loc l1 _) == IgnoreFormat (Loc l2 _) = l1 == l2+instance Ord (IgnoreFormat Loc) where+  compare (IgnoreFormat (Loc l1 _)) (IgnoreFormat (Loc l2 _)) = compare l1 l2++instance Outputable VLoc where         ppr l = text (show l) +instance Outputable Loc where+  ppr (Loc loc fmt) = parens (ppr loc <+> dcolon <+> ppr fmt)+ -- | A 'RealReg', together with the specific 'Format' it is used at. data RealRegUsage   = RealRegUsage@@ -122,21 +146,11 @@ instance Outputable RealRegUsage where   ppr (RealRegUsage r fmt) = ppr r <> dcolon <+> ppr fmt --- NB: these instances only compare the underlying 'RealReg', as that is what--- is important for register allocation.------ (It would nonetheless be a good idea to remove these instances.)-instance Eq RealRegUsage where-  (==) = (==) `on` realReg-instance Ord RealRegUsage where-  compare = compare `on` realReg- -- | Get the reg numbers stored in this Loc.-regsOfLoc :: Loc -> [RealRegUsage]+regsOfLoc :: VLoc -> [RealReg] regsOfLoc (InReg r)    = [r] regsOfLoc (InBoth r _) = [r] regsOfLoc (InMem _)    = []-  -- | Reasons why instructions might be inserted by the spiller. --      Used when generating stats for -ddrop-asm-stats.
GHC/CmmToAsm/Reg/Linear/JoinToTargets.hs view
@@ -33,12 +33,14 @@ import GHC.CmmToAsm.Format import GHC.Types.Unique.Set +import Data.Coerce (coerce)+ -- | For a jump instruction at the end of a block, generate fixup code so its --      vregs are in the correct regs for its destination. -- joinToTargets         :: (FR freeRegs, Instruction instr)-        => BlockMap (UniqSet RegWithFormat) -- ^ maps the unique of the blockid to the set of vregs+        => BlockMap Regs -- ^ maps the unique of the blockid to the set of vregs                                         --      that are known to be live on the entry to each block.          -> BlockId                      -- ^ id of the current block@@ -62,7 +64,7 @@ ----- joinToTargets'         :: (FR freeRegs, Instruction instr)-        => BlockMap (UniqSet RegWithFormat) -- ^ maps the unique of the blockid to the set of vregs+        => BlockMap Regs -- ^ maps the unique of the blockid to the set of vregs                                         --      that are known to be live on the entry to each block.          -> [NatBasicBlock instr]        -- ^ acc blocks of fixup code.@@ -90,23 +92,23 @@         -- adjust the current assignment to remove any vregs that are not live         -- on entry to the destination block.         let live_set            = expectJust $ mapLookup dest block_live-        let still_live uniq _   = uniq `elemUniqSet_Directly` live_set+        let still_live uniq _   = uniq `elemUniqSet_Directly` getRegs live_set         let adjusted_assig      = filterUFM_Directly still_live assig          -- and free up those registers which are now free.         let to_free =-                [ r     | (reg, loc) <- nonDetUFMToList assig+                [ r     | (reg, Loc loc _locFmt) <- nonDetUFMToList assig                         -- This is non-deterministic but we do not                         -- currently support deterministic code-generation.                         -- See Note [Unique Determinism and code generation]-                        , not (elemUniqSet_Directly reg live_set)+                        , not (elemUniqSet_Directly reg $ getRegs live_set)                         , r          <- regsOfLoc loc ]          case lookupBlockAssignment  dest block_assig of          Nothing           -> joinToTargets_first                         block_live new_blocks block_id instr dest dests-                        block_assig adjusted_assig $ map realReg to_free+                        block_assig adjusted_assig to_free           Just (_, dest_assig)           -> joinToTargets_again@@ -116,7 +118,7 @@  -- this is the first time we jumped to this block. joinToTargets_first :: (FR freeRegs, Instruction instr)-                    => BlockMap (UniqSet RegWithFormat)+                    => BlockMap Regs                     -> [NatBasicBlock instr]                     -> BlockId                     -> instr@@ -142,10 +144,9 @@          joinToTargets' block_live new_blocks block_id instr dests - -- we've jumped to this block before joinToTargets_again :: (Instruction instr, FR freeRegs)-                    => BlockMap (UniqSet RegWithFormat)+                    => BlockMap Regs                     -> [NatBasicBlock instr]                     -> BlockId                     -> instr@@ -159,7 +160,9 @@     src_assig dest_assig          -- the assignments already match, no problem.-        | nonDetUFMToList dest_assig == nonDetUFMToList src_assig+        | equalIgnoringFormats+            (nonDetUFMToList dest_assig)+            (nonDetUFMToList src_assig)         -- This is non-deterministic but we do not         -- currently support deterministic code-generation.         -- See Note [Unique Determinism and code generation]@@ -183,7 +186,7 @@                 --                 -- We need to do the R2 -> R3 move before R1 -> R2.                 ---                let sccs  = stronglyConnCompFromEdgedVerticesOrdR graph+                let sccs  = movementGraphSCCs graph                -- debugging                 {-@@ -267,30 +270,36 @@ -- expandNode         :: a-        -> Loc                  -- ^ source of move-        -> Loc                  -- ^ destination of move-        -> [Node Loc a ]--expandNode vreg loc@(InReg src) (InBoth dst mem)-        | src == dst = [DigraphNode vreg loc [InMem mem]]-        | otherwise  = [DigraphNode vreg loc [InReg dst, InMem mem]]--expandNode vreg loc@(InMem src) (InBoth dst mem)-        | src == mem = [DigraphNode vreg loc [InReg dst]]-        | otherwise  = [DigraphNode vreg loc [InReg dst, InMem mem]]--expandNode _        (InBoth _ src) (InMem dst)-        | src == dst = [] -- guaranteed to be true--expandNode _        (InBoth src _) (InReg dst)-        | src == dst = []--expandNode vreg     (InBoth src _) dst-        = expandNode vreg (InReg src) dst--expandNode vreg src dst-        | src == dst = []-        | otherwise  = [DigraphNode vreg src [dst]]+        -> Loc -- ^ source of move+        -> Loc -- ^ destination of move+        -> [Node Loc a]+expandNode vreg src@(Loc srcLoc srcFmt) dst@(Loc dstLoc dstFmt) =+  case (srcLoc, dstLoc) of+    (InReg srcReg, InBoth dstReg dstMem)+        | srcReg == dstReg+        -> [DigraphNode vreg src [Loc (InMem dstMem) dstFmt]]+        | otherwise+        -> [DigraphNode vreg src [Loc (InReg dstReg) dstFmt+                                 ,Loc (InMem dstMem) dstFmt]]+    (InMem srcMem, InBoth dstReg dstMem)+        | srcMem == dstMem+        -> [DigraphNode vreg src [Loc (InReg dstReg) dstFmt]]+        | otherwise+        -> [DigraphNode vreg src [Loc (InReg dstReg) dstFmt+                                 ,Loc (InMem dstMem) dstFmt]]+    (InBoth _ srcMem, InMem dstMem)+        | srcMem == dstMem+        -> [] -- guaranteed to be true+    (InBoth srcReg _, InReg dstReg)+        | srcReg == dstReg+        -> []+    (InBoth srcReg _, _)+        -> expandNode vreg (Loc (InReg srcReg) srcFmt) dst+    _+      | srcLoc == dstLoc+      -> []+      | otherwise+      -> [DigraphNode vreg src [dst]]   -- | Generate fixup code for a particular component in the move graph@@ -327,7 +336,7 @@ --      require a fixup. -- handleComponent delta instr-        (CyclicSCC ((DigraphNode vreg (InReg (RealRegUsage sreg scls)) ((InReg (RealRegUsage dreg dcls): _))) : rest))+        (CyclicSCC ((DigraphNode vreg (Loc (InReg sreg) scls) ((Loc (InReg dreg) dcls: _))) : rest))         -- dest list may have more than one element, if the reg is also InMem.  = do         -- spill the source into its slot@@ -338,7 +347,7 @@         instrLoad       <- loadR (RegWithFormat (RegReal dreg) dcls) slot          remainingFixUps <- mapM (handleComponent delta instr)-                                (stronglyConnCompFromEdgedVerticesOrdR rest)+                                (movementGraphSCCs rest)          -- make sure to do all the reloads after all the spills,         --      so we don't end up clobbering the source values.@@ -347,29 +356,37 @@ handleComponent _ _ (CyclicSCC _)  = panic "Register Allocator: handleComponent cyclic" +-- Helper functions that use the @Ord (IgnoreFormat Loc)@ instance. +equalIgnoringFormats :: [(Unique, Loc)] -> [(Unique, Loc)] -> Bool+equalIgnoringFormats =+  coerce $ (==) @[(Unique, IgnoreFormat Loc)]+movementGraphSCCs :: [Node Loc Unique] -> [SCC (Node Loc Unique)]+movementGraphSCCs =+  coerce $ stronglyConnCompFromEdgedVerticesOrdR @(IgnoreFormat Loc) @Unique+ -- | Move a vreg between these two locations. -- makeMove     :: Instruction instr-    => Int      -- ^ current C stack delta.-    -> Unique   -- ^ unique of the vreg that we're moving.-    -> Loc      -- ^ source location.-    -> Loc      -- ^ destination location.-    -> RegM freeRegs [instr]  -- ^ move instruction.+    => Int           -- ^ current C stack delta+    -> Unique        -- ^ unique of the vreg that we're moving+    -> Loc -- ^ source location+    -> Loc -- ^ destination location+    -> RegM freeRegs [instr]  -- ^ move instruction -makeMove delta vreg src dst+makeMove delta vreg (Loc src _srcFmt) (Loc dst dstFmt)  = do config <- getConfig       case (src, dst) of-          (InReg (RealRegUsage s _), InReg (RealRegUsage d fmt)) ->+          (InReg s, InReg d) ->               do recordSpill (SpillJoinRR vreg)-                 return $ [mkRegRegMoveInstr config fmt (RegReal s) (RegReal d)]-          (InMem s, InReg (RealRegUsage d cls)) ->+                 return $ [mkRegRegMoveInstr config dstFmt (RegReal s) (RegReal d)]+          (InMem s, InReg d) ->               do recordSpill (SpillJoinRM vreg)-                 return $ mkLoadInstr config (RegWithFormat (RegReal d) cls) delta s-          (InReg (RealRegUsage s cls), InMem d) ->+                 return $ mkLoadInstr config (RegWithFormat (RegReal d) dstFmt) delta s+          (InReg s, InMem d) ->               do recordSpill (SpillJoinRM vreg)-                 return $ mkSpillInstr config (RegWithFormat (RegReal s) cls) delta d+                 return $ mkSpillInstr config (RegWithFormat (RegReal s) dstFmt) delta d           _ ->               -- we don't handle memory to memory moves.               -- they shouldn't happen because we don't share
GHC/CmmToAsm/Reg/Linear/StackMap.hs view
@@ -37,7 +37,11 @@            -- See Note [UniqFM and the register allocator]           -- | Assignment of vregs to stack slots.-        , stackMapAssignment    :: UniqFM Unique StackSlot }+          --+          -- We record not just the slot, but also how many stack slots the vreg+          -- takes up, in order to avoid re-using a stack slot for a register+          -- that has grown but already had a stack slot (#26668).+        , stackMapAssignment    :: UniqFM Unique (StackSlot, Int) }   -- | An empty stack map, with all slots available.@@ -50,14 +54,19 @@ -- getStackSlotFor :: StackMap -> Format -> Unique -> (StackMap, Int) -getStackSlotFor fs@(StackMap _ reserved) _fmt regUnique-  | Just slot <- lookupUFM reserved regUnique  =  (fs, slot)--getStackSlotFor (StackMap freeSlot reserved) fmt regUnique =-  let-    nbSlots = (formatInBytes fmt + 7) `div` 8-  in-    (StackMap (freeSlot+nbSlots) (addToUFM reserved regUnique freeSlot), freeSlot)+getStackSlotFor fs@(StackMap freeSlot reserved) fmt regUnique+  -- The register already has a stack slot; try to re-use it.+  | Just (slot, nbSlots) <- lookupUFM reserved regUnique+  -- Make sure the slot is big enough for this format, in case the register+  -- has grown (#26668).+  , nbNeededSlots <= nbSlots+  = (fs, slot)+  | otherwise+  = (StackMap (freeSlot+nbNeededSlots) (addToUFM reserved regUnique (freeSlot, nbNeededSlots)), freeSlot)+    -- NB: this can create fragmentation if a register keeps growing.+    -- That's probably OK, as this is only happens very rarely.+  where+    !nbNeededSlots = (formatInBytes fmt + 7) `div` 8  -- | Return the number of stack slots that were allocated getStackUse :: StackMap -> Int
GHC/CmmToAsm/Reg/Liveness.hs view
@@ -30,7 +30,9 @@         patchRegsLiveInstr,         reverseBlocksInTops,         regLiveness,-        cmmTopLiveness+        cmmTopLiveness,++        module GHC.CmmToAsm.Reg.Regs   ) where import GHC.Prelude @@ -41,13 +43,14 @@ import GHC.CmmToAsm.Format import GHC.CmmToAsm.Types import GHC.CmmToAsm.Utils+import GHC.CmmToAsm.Reg.Regs  import GHC.Cmm.BlockId import GHC.Cmm.Dataflow.Label import GHC.Cmm-import GHC.CmmToAsm.Reg.Target  import GHC.Data.Graph.Directed+import GHC.Data.OrdList import GHC.Utils.Monad import GHC.Utils.Outputable import GHC.Utils.Panic@@ -188,9 +191,9 @@  data Liveness         = Liveness-        { liveBorn      :: UniqSet RegWithFormat      -- ^ registers born in this instruction (written to for first time).-        , liveDieRead   :: UniqSet RegWithFormat      -- ^ registers that died because they were read for the last time.-        , liveDieWrite  :: UniqSet RegWithFormat}     -- ^ registers that died because they were clobbered by something.+        { liveBorn      :: Regs      -- ^ registers born in this instruction (written to for first time).+        , liveDieRead   :: Regs      -- ^ registers that died because they were read for the last time.+        , liveDieWrite  :: Regs }    -- ^ registers that died because they were clobbered by something.   -- | Stash regs live on entry to each basic block in the info part of the cmm code.@@ -199,7 +202,7 @@                 (LabelMap RawCmmStatics)  -- cmm info table static stuff                 [BlockId]                 -- entry points (first one is the                                           -- entry point for the proc).-                (BlockMap (UniqSet RegWithFormat))         -- argument locals live on entry to this block+                (BlockMap Regs)       -- argument locals live on entry to this block                 (BlockMap IntSet)         -- stack slots live on entry to this block  @@ -245,8 +248,8 @@                         , pprRegs (text "# w_dying: ") (liveDieWrite live) ]                     $+$ space) -         where  pprRegs :: SDoc -> UniqSet RegWithFormat -> SDoc-                pprRegs name regs+         where  pprRegs :: SDoc -> Regs -> SDoc+                pprRegs name ( Regs regs )                  | isEmptyUniqSet regs  = empty                  | otherwise            = name <>                      (pprUFM (getUniqSet regs) (hcat . punctuate space . map ppr))@@ -329,7 +332,7 @@         :: Instruction instr         => Platform         -> LiveCmmDecl statics instr-        -> (Bag (UniqSet RegWithFormat), Bag (Reg, Reg))+        -> (Bag Regs, Bag (Reg, Reg))  slurpConflicts platform live         = slurpCmm (emptyBag, emptyBag) live@@ -363,23 +366,22 @@          = let                 -- regs that die because they are read for the last time at the start of an instruction                 --      are not live across it.-                rsLiveAcross    = rsLiveEntry `minusUniqSet` (liveDieRead live)+                rsLiveAcross    = rsLiveEntry `minusRegs` (liveDieRead live)                  -- regs live on entry to the next instruction.                 --      be careful of orphans, make sure to delete dying regs _after_ unioning                 --      in the ones that are born here.-                rsLiveNext      = (rsLiveAcross `unionUniqSets` (liveBorn     live))-                                                `minusUniqSet`  (liveDieWrite live)+                rsLiveNext      = (rsLiveAcross `unionRegsMaxFmt`  (liveBorn     live))+                                                `minusCoveredRegs` (liveDieWrite live)                  -- orphan vregs are the ones that die in the same instruction they are born in.                 --      these are likely to be results that are never used, but we still                 --      need to assign a hreg to them..-                rsOrphans       = intersectUniqSets+                rsOrphans       = intersectRegsMaxFmt                                         (liveBorn live)-                                        (unionUniqSets (liveDieWrite live) (liveDieRead live))+                                        (unionRegsMaxFmt (liveDieWrite live) (liveDieRead live)) -                ---                rsConflicts     = unionUniqSets rsLiveNext rsOrphans+                rsConflicts     = unionRegsMaxFmt rsLiveNext rsOrphans            in    case takeRegRegMoveInstr platform instr of                  Just rr        -> slurpLIs rsLiveNext@@ -562,30 +564,26 @@  =      BasicBlock i instrs'   where  (instrs', _)-                = runState (spillNat [] lis) 0+                = runState (spillNat nilOL lis) 0 -        -- spillNat :: [instr] -> [LiveInstr instr] -> State Int [instr]-        spillNat :: Instruction instr => [instr] -> [LiveInstr instr] -> State Int [instr]+        spillNat :: Instruction instr => OrdList instr -> [LiveInstr instr] -> State Int [instr]         spillNat acc []-         =      return (reverse acc)+         =      return (fromOL acc) -        -- The SPILL/RELOAD cases do not appear to be exercised by our codegens-        --         spillNat acc (LiveInstr (SPILL reg slot) _ : instrs)          = do   delta   <- get-                spillNat (mkSpillInstr config reg delta slot ++ acc) instrs+                spillNat (acc `appOL` toOL (mkSpillInstr config reg delta slot)) instrs          spillNat acc (LiveInstr (RELOAD slot reg) _ : instrs)          = do   delta   <- get-                spillNat (mkLoadInstr config reg delta slot ++ acc) instrs+                spillNat (acc `appOL` toOL (mkLoadInstr config reg delta slot)) instrs          spillNat acc (LiveInstr (Instr instr) _ : instrs)          | Just i <- takeDeltaInstr instr          = do   put i                 spillNat acc instrs--        spillNat acc (LiveInstr (Instr instr) _ : instrs)-         =      spillNat (instr : acc) instrs+         | otherwise+         =      spillNat (acc `snocOL` instr) instrs   -- | Erase Delta instructions.@@ -622,7 +620,7 @@          | LiveInfo static id blockMap mLiveSlots <- info          = let                   -- See Note [Unique Determinism and code generation]-                blockMap'       = mapMap (mapRegFormatSet patchF) blockMap+                blockMap'       = mapMap (mapRegs patchF) blockMap                  info'           = LiveInfo static id blockMap' mLiveSlots            in   CmmProc info' label live $ map patchSCC sccs@@ -651,8 +649,8 @@                 | r1 == r2      = True                  -- destination reg is never used-                | elemUniqSet_Directly (getUnique r2) (liveBorn live)-                , elemUniqSet_Directly (getUnique r2) (liveDieRead live) || elemUniqSet_Directly (getUnique r2) (liveDieWrite live)+                | r2 `elemRegs` liveBorn live+                , r2 `elemRegs` liveDieRead live || r2 `elemRegs` liveDieWrite live                 = True                  | otherwise     = False@@ -676,9 +674,9 @@                 (patchRegsOfInstr platform instr patchF)                 (Just live                         { -- WARNING: have to go via lists here because patchF changes the uniq in the Reg-                          liveBorn      = mapRegFormatSet patchF $ liveBorn live-                        , liveDieRead   = mapRegFormatSet patchF $ liveDieRead live-                        , liveDieWrite  = mapRegFormatSet patchF $ liveDieWrite live })+                          liveBorn      = mapRegs patchF $ liveBorn live+                        , liveDieRead   = mapRegs patchF $ liveDieRead live+                        , liveDieWrite  = mapRegs patchF $ liveDieWrite live })                           -- See Note [Unique Determinism and code generation]  --------------------------------------------------------------------------------@@ -868,7 +866,7 @@         -> [SCC (LiveBasicBlock instr)]         -> ([SCC (LiveBasicBlock instr)],       -- instructions annotated with list of registers                                                 -- which are "dead after this instruction".-               BlockMap (UniqSet RegWithFormat))                 -- blocks annotated with set of live registers+               BlockMap Regs)               -- blocks annotated with set of live registers                                                 -- on entry to the block.  computeLiveness platform sccs@@ -883,11 +881,11 @@ livenessSCCs        :: Instruction instr        => Platform-       -> BlockMap (UniqSet RegWithFormat)+       -> BlockMap Regs        -> [SCC (LiveBasicBlock instr)]          -- accum        -> [SCC (LiveBasicBlock instr)]        -> ( [SCC (LiveBasicBlock instr)]-          , BlockMap (UniqSet RegWithFormat))+          , BlockMap Regs)  livenessSCCs _ blockmap done []         = (done, blockmap)@@ -916,13 +914,14 @@              linearLiveness                 :: Instruction instr-                => BlockMap (UniqSet RegWithFormat) -> [LiveBasicBlock instr]-                -> (BlockMap (UniqSet RegWithFormat), [LiveBasicBlock instr])+                => BlockMap Regs -> [LiveBasicBlock instr]+                -> (BlockMap Regs, [LiveBasicBlock instr])              linearLiveness = mapAccumL (livenessBlock platform)                  -- probably the least efficient way to compare two                 -- BlockMaps for equality.+            equalBlockMaps :: BlockMap Regs -> BlockMap Regs -> Bool             equalBlockMaps a b                 = a' == b'               where a' = mapToList a@@ -936,14 +935,14 @@ livenessBlock         :: Instruction instr         => Platform-        -> BlockMap (UniqSet RegWithFormat)+        -> BlockMap Regs         -> LiveBasicBlock instr-        -> (BlockMap (UniqSet RegWithFormat), LiveBasicBlock instr)+        -> (BlockMap Regs, LiveBasicBlock instr)  livenessBlock platform blockmap (BasicBlock block_id instrs)  = let         (regsLiveOnEntry, instrs1)-            = livenessBack platform emptyUniqSet blockmap [] (reverse instrs)+            = livenessBack platform noRegs blockmap [] (reverse instrs)         blockmap'       = mapInsert block_id regsLiveOnEntry blockmap          instrs2         = livenessForward platform regsLiveOnEntry instrs1@@ -958,23 +957,26 @@ livenessForward         :: Instruction instr         => Platform-        -> UniqSet RegWithFormat -- regs live on this instr+        -> Regs -- regs live on this instr         -> [LiveInstr instr] -> [LiveInstr instr]  livenessForward _        _           []  = [] livenessForward platform rsLiveEntry (li@(LiveInstr instr mLive) : lis)         | Just live <- mLive         = let-                RU _ written  = regUsageOfInstr platform instr+                RU _ rsWritten  = regUsageOfInstr platform instr                 -- Regs that are written to but weren't live on entry to this instruction                 --      are recorded as being born here.-                rsBorn          = mkUniqSet-                                $ filter (\ r -> not $ elemUniqSet_Directly (getUnique r) rsLiveEntry)-                                $ written+                rsBorn          = mkRegsMaxFmt+                                    [ reg+                                    | reg@( RegWithFormat r _ ) <- rsWritten+                                    , not $ r `elemRegs` rsLiveEntry+                                    ] -                rsLiveNext      = (rsLiveEntry `unionUniqSets` rsBorn)-                                        `minusUniqSet` (liveDieRead live)-                                        `minusUniqSet` (liveDieWrite live)+                   -- See Note [Register formats in liveness analysis]+                rsLiveNext      = (rsLiveEntry `addRegsMaxFmt` rsWritten)+                                        `minusRegs` (liveDieRead live)  -- (FmtFwd1)+                                        `minusRegs` (liveDieWrite live) -- (FmtFwd2)          in LiveInstr instr (Just live { liveBorn = rsBorn })                 : livenessForward platform rsLiveNext lis@@ -989,11 +991,11 @@ livenessBack         :: Instruction instr         => Platform-        -> UniqSet RegWithFormat            -- regs live on this instr-        -> BlockMap (UniqSet RegWithFormat) -- regs live on entry to other BBs-        -> [LiveInstr instr]            -- instructions (accum)-        -> [LiveInstr instr]            -- instructions-        -> (UniqSet RegWithFormat, [LiveInstr instr])+        -> Regs           -- ^ regs live on this instr+        -> BlockMap Regs  -- ^ regs live on entry to other BBs+        -> [LiveInstr instr]  -- ^ instructions (accum)+        -> [LiveInstr instr]  -- ^ instructions+        -> (Regs, [LiveInstr instr])  livenessBack _        liveregs _        done []  = (liveregs, done) @@ -1001,15 +1003,14 @@  = let  !(!liveregs', instr')     = liveness1 platform liveregs blockmap instr    in   livenessBack platform liveregs' blockmap (instr' : acc) instrs - -- don't bother tagging comments or deltas with liveness liveness1         :: Instruction instr         => Platform-        -> UniqSet RegWithFormat-        -> BlockMap (UniqSet RegWithFormat)+        -> Regs+        -> BlockMap Regs         -> LiveInstr instr-        -> (UniqSet RegWithFormat, LiveInstr instr)+        -> (Regs, LiveInstr instr)  liveness1 _ liveregs _ (LiveInstr instr _)         | isMetaInstr instr@@ -1020,14 +1021,14 @@         | not_a_branch         = (liveregs1, LiveInstr instr                         (Just $ Liveness-                        { liveBorn      = emptyUniqSet+                        { liveBorn      = noRegs                         , liveDieRead   = r_dying                         , liveDieWrite  = w_dying }))          | otherwise         = (liveregs_br, LiveInstr instr                         (Just $ Liveness-                        { liveBorn      = emptyUniqSet+                        { liveBorn      = noRegs                         , liveDieRead   = r_dying_br                         , liveDieWrite  = w_dying })) @@ -1036,21 +1037,22 @@              -- registers that were written here are dead going backwards.             -- registers that were read here are live going backwards.-            liveregs1   = (liveregs `delListFromUniqSet` written)-                                    `addListToUniqSet` read+            -- As for the formats, see Note [Register formats in liveness analysis]+            liveregs1   = (liveregs `minusCoveredRegs` mkRegsMaxFmt written) -- (FmtBwd2)+                                    `addRegsMaxFmt` read                     -- (FmtBwd1) -            -- registers that are not live beyond this point, are recorded-            --  as dying here.-            r_dying     = mkUniqSet+            -- registers that are not live beyond this point are recorded+            -- as dying here.+            r_dying     = mkRegsMaxFmt                           [ reg                           | reg@(RegWithFormat r _) <- read                           , not $ any (\ w -> getUnique w == getUnique r) written-                          , not (elementOfUniqSet reg liveregs) ]+                          , not $ r `elemRegs` liveregs ] -            w_dying     = mkUniqSet+            w_dying     = mkRegsMaxFmt                           [ reg-                          | reg <- written-                          , not (elementOfUniqSet reg liveregs) ]+                          | reg@(RegWithFormat r _) <- written+                          , not $ r `elemRegs` liveregs ]              -- union in the live regs from all the jump destinations of this             -- instruction.@@ -1060,14 +1062,91 @@             targetLiveRegs target                   = case mapLookup target blockmap of                                 Just ra -> ra-                                Nothing -> emptyUniqSet--            live_from_branch = unionManyUniqSets (map targetLiveRegs targets)--            liveregs_br = liveregs1 `unionUniqSets` live_from_branch+                                Nothing -> noRegs              -- registers that are live only in the branch targets should             -- be listed as dying here.-            live_branch_only = live_from_branch `minusUniqSet` liveregs-            r_dying_br  = (r_dying `unionUniqSets` live_branch_only)-                          -- See Note [Unique Determinism and code generation]+            live_from_branch = unionManyRegsMaxFmt (map targetLiveRegs targets)+            liveregs_br = liveregs1 `unionRegsMaxFmt` live_from_branch+            live_branch_only = live_from_branch `minusRegs` liveregs+            r_dying_br  = r_dying `unionRegsMaxFmt` live_branch_only+              -- NB: we treat registers live in branches similar to any other+              -- registers read by the instruction, so the logic here matches+              -- the logic in the definition of 'r_dying' above.++{- Note [Register formats in liveness analysis]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+We keep track of which format each virtual register is live at, and make use+of this information during liveness analysis.++First, we do backwards liveness analysis:++  (FmtBwd1) Take the larger format when computing registers live going backwards.++    Suppose for example that we have:++      <previous instructions>+      movps  %v0 %v1+      movupd %v0 %v2++    Here we read %v0 both at format F64 and F64x2, so we must consider it live+    at format F64x2, going backwards, in the previous instructions.+    Not doing so caused #26411.++  (FmtBwd2) Only consider fully clobbered registers to be dead going backwards.++    Consider for example the liveness of %v0 going backwards in the following+    instruction block:++      movlhps %v5 %v0  -- write the upper F64 of %v0+      movupd  %v1 %v2  -- some unrelated instruction+      movsd   %v3 %v0  -- write the lower F64 of %v0+      movupd  %v0 %v4  -- read %v0 at format F64x2++    We must not consider %v0 to be dead going backwards from 'movsd %v3 %v0'.+    If we do, that means we think %v0 is dead during 'movupd %v1 %v2', and thus+    that we can assign both %v0 and %v2 to the same real register. However, this+    would be catastrophic, as 'movupd %v1 %v2' would then clobber the data+    written to '%v0' in 'movlhps %v5 %v0'.++    Wrinkle [Don't allow scalar partial writes]++      We don't allow partial writes within scalar registers, for many reasons:++        - partial writes can cause partial register stalls, which can have+          disastrous performance implications (as seen in #20405)+        - partial writes makes register allocation more difficult, as they can+          require preserving the contents of a register across many instructions,+          as in:++            mulw %v0             -- 32-bit write to %rax+            <many instructions>+            mulb %v1             -- 16-bit partial write to %rax++          The current register allocator is not equipped for spilling real+          registers (only virtual registers), which means that e.g. on i386 we+          end up with only 2 allocatable real GP registers for <many instructions>,+          which is insufficient for instructions that require 3 registers.++      We could allow this to be customised depending on the architecture, but+      currently we simply never allow scalar partial writes.++The forwards analysis is a bit simpler:++  (FmtFwd1) Remove without considering format when dead going forwards.++    If a register is no longer read after an instruction, then it is dead+    going forwards. The format doesn't matter.++  (FmtFwd2) Consider all writes as making a register dead going forwards.++    If we write to the lower 64 bits of a 128 bit register, we don't currently+    have a way to say "the lower 64 bits are dead but the top 64 bits are still live".+    We would need a notion of partial register, similar to 'VirtualRegHi' for+    the top 32 bits of a I32x2 virtual register.++    As a result, the current approach is to consider the entire register to+    be dead. This might cause us to unnecessarily spill/reload an entire vector+    register to avoid its lower bits getting clobbered even though later+    instructions might only care about its upper bits.+-}
+ GHC/CmmToAsm/Reg/Regs.hs view
@@ -0,0 +1,119 @@+{-# LANGUAGE DerivingStrategies #-}++module GHC.CmmToAsm.Reg.Regs (+        Regs(..),+        noRegs,+        addRegMaxFmt, addRegsMaxFmt,+        mkRegsMaxFmt,+        minusCoveredRegs,+        minusRegs,+        unionRegsMaxFmt,+        unionManyRegsMaxFmt,+        intersectRegsMaxFmt,+        shrinkingRegs,+        mapRegs,+        elemRegs, lookupReg,++  ) where++import GHC.Prelude++import GHC.Platform.Reg     ( Reg )+import GHC.CmmToAsm.Format  ( Format, RegWithFormat(..), isVecFormat )++import GHC.Utils.Outputable ( Outputable )+import GHC.Types.Unique     ( Uniquable(..) )+import GHC.Types.Unique.Set++import Data.Coerce ( coerce )++-----------------------------------------------------------------------------++-- | A set of registers, with their respective formats, mostly for use in+-- register liveness analysis.  See Note [Register formats in liveness analysis]+-- in GHC.CmmToAsm.Reg.Liveness.+newtype Regs = Regs { getRegs :: UniqSet RegWithFormat }+  deriving newtype (Eq, Outputable)++maxRegWithFormat :: RegWithFormat -> RegWithFormat -> RegWithFormat+maxRegWithFormat r1@(RegWithFormat _ fmt1) r2@(RegWithFormat _ fmt2)+  = if fmt1 >= fmt2+    then r1+    else r2+  -- Re-using one of the arguments avoids allocating a new 'RegWithFormat',+  -- compared with returning 'RegWithFormat r1 (max fmt1 fmt2)'.++noRegs :: Regs+noRegs = Regs emptyUniqSet++addRegsMaxFmt :: Regs -> [RegWithFormat] -> Regs+addRegsMaxFmt = foldl' addRegMaxFmt++mkRegsMaxFmt :: [RegWithFormat] -> Regs+mkRegsMaxFmt = addRegsMaxFmt noRegs++addRegMaxFmt :: Regs -> RegWithFormat -> Regs+addRegMaxFmt = coerce $ strictAddOneToUniqSet_C maxRegWithFormat+  -- Don't build up thunks when combining with 'maxRegWithFormat'++-- | Remove 2nd argument registers from the 1st argument, but only+-- if the format in the second argument is at least as large as the format+-- in the first argument.+minusCoveredRegs :: Regs -> Regs -> Regs+minusCoveredRegs = coerce $ minusUniqSet_C f+  where+    f :: RegWithFormat -> RegWithFormat -> Maybe RegWithFormat+    f r1@(RegWithFormat _ fmt1) (RegWithFormat _ fmt2) =+      if fmt2 >= fmt1+           ||+         not ( isVecFormat fmt1 )+          -- See Wrinkle [Don't allow scalar partial writes]+          -- in Note [Register formats in liveness analysis] in GHC.CmmToAsm.Reg.Liveness.+      then Nothing+      else Just r1++-- | Remove 2nd argument registers from the 1st argument, regardless of format.+--+-- See also 'minusCoveredRegs', which looks at the formats.+minusRegs :: Regs -> Regs -> Regs+minusRegs = coerce $ minusUniqSet @RegWithFormat++unionRegsMaxFmt :: Regs -> Regs -> Regs+unionRegsMaxFmt = coerce $ strictUnionUniqSets_C maxRegWithFormat+  -- Don't build up thunks when combining with 'maxRegWithFormat'++unionManyRegsMaxFmt :: [Regs] -> Regs+unionManyRegsMaxFmt = coerce $ strictUnionManyUniqSets_C maxRegWithFormat+  -- Don't build up thunks when combining with 'maxRegWithFormat'++intersectRegsMaxFmt :: Regs -> Regs -> Regs+intersectRegsMaxFmt = coerce $ strictIntersectUniqSets_C maxRegWithFormat+  -- Don't build up thunks when combining with 'maxRegWithFormat'++-- | Computes the set of registers in both arguments whose size is smaller in+-- the second argument than in the first.+shrinkingRegs :: Regs -> Regs -> Regs+shrinkingRegs = coerce $ minusUniqSet_C f+  where+    f :: RegWithFormat -> RegWithFormat -> Maybe RegWithFormat+    f (RegWithFormat _ fmt1) r2@(RegWithFormat _ fmt2)+      | fmt2 < fmt1+      = Just r2+      | otherwise+      = Nothing++-- | Map a function that may change the 'Unique' of the register,+-- which entails going via lists.+--+-- See Note [UniqSet invariant] in GHC.Types.Unique.Set.+mapRegs :: (Reg -> Reg) -> Regs -> Regs+mapRegs f (Regs live) =+  Regs $+    mapUniqSet (\ (RegWithFormat r fmt) -> RegWithFormat (f r) fmt) live++elemRegs :: Reg -> Regs -> Bool+elemRegs r (Regs live) = elemUniqSet_Directly (getUnique r) live++lookupReg :: Reg -> Regs -> Maybe Format+lookupReg r (Regs live) =+  regWithFormat_format <$> lookupUniqSet_Directly live (getUnique r)
GHC/CmmToAsm/Reg/Target.hs view
@@ -15,7 +15,6 @@         targetMkVirtualReg,         targetRegDotColor,         targetClassOfReg,-        mapRegFormatSet, )  where@@ -27,10 +26,8 @@ import GHC.CmmToAsm.Format  import GHC.Utils.Outputable-import GHC.Utils.Misc import GHC.Utils.Panic import GHC.Types.Unique-import GHC.Types.Unique.Set import GHC.Platform  import qualified GHC.CmmToAsm.X86.Regs       as X86@@ -142,6 +139,3 @@  = case reg of    RegVirtual vr -> classOfVirtualReg (platformArch platform) vr    RegReal rr -> targetClassOfRealReg platform rr--mapRegFormatSet :: HasDebugCallStack => (Reg -> Reg) -> UniqSet RegWithFormat -> UniqSet RegWithFormat-mapRegFormatSet f = mapUniqSet (\ ( RegWithFormat r fmt ) -> RegWithFormat ( f r ) fmt)
GHC/CmmToAsm/Wasm/FromCmm.hs view
@@ -113,7 +113,7 @@ -- | Calculate a data section's kind, see haddock docs of -- 'DataSectionKind' for more explanation. dataSectionKindFromCmmSection :: Section -> DataSectionKind-dataSectionKindFromCmmSection s = case sectionProtection s of+dataSectionKindFromCmmSection (Section t _) = case sectionProtection t of   ReadWriteSection -> SectionData   _ -> SectionROData 
GHC/CmmToAsm/X86/CodeGen.hs view
@@ -57,7 +57,9 @@ import GHC.CmmToAsm.Format import GHC.CmmToAsm.Config import GHC.Platform.Reg+import GHC.CmmToAsm.Reg.Target (targetClassOfReg) import GHC.Platform+import GHC.Platform.Reg.Class.Unified (RegClass(..))  -- Our intermediate code: import GHC.Types.Basic@@ -4669,7 +4671,14 @@         -- It's not safe to omit this assignment, even if the number         -- of SSE2 regs in use is zero.  If %al is larger than 8         -- on entry to a varargs function, seg faults ensue.-        nb_sse_regs_used = count (isFloatFormat . regWithFormat_format) arg_regs_used+        is_sse_reg (RegWithFormat r _) =+          -- NB: use 'targetClassOfRealReg' to compute whether this is an SSE+          -- register or not, as we may have decided to e.g. store a 64-bit+          -- integer in an xmm register.+          case targetClassOfReg platform r of+            RcFloatOrVector -> True+            RcInteger       -> False+        nb_sse_regs_used = count is_sse_reg arg_regs_used         assign_eax_sse_regs           = unitOL (MOV II32 (OpImm (ImmInt nb_sse_regs_used)) (OpReg eax))           -- Note: we do this on Windows as well. It's not entirely clear why
GHC/CmmToAsm/X86/Instr.hs view
@@ -115,9 +115,12 @@          -- | X86 scalar move instruction.         ---        -- When used at a vector format, only moves the lower 64 bits of data;-        -- the rest of the data in the destination may either be zeroed or-        -- preserved, depending on the specific format and operands.+        -- The format is the format the destination is written to. For an XMM+        -- register, using a scalar format means that we don't care about the+        -- upper bits, while using a vector format means that we care about the+        -- upper bits, even though we are only writing to the lower bits.+        --+        -- See also Note [Allocated register formats] in GHC.CmmToAsm.Reg.Linear.         | MOV Format Operand Operand              -- N.B. Due to AT&T assembler quirks, when used with 'II64'              -- 'Format' immediate source and memory target operand, the source@@ -406,18 +409,27 @@ regUsageOfInstr :: Platform -> Instr -> RegUsage regUsageOfInstr platform instr  = case instr of-    MOV fmt src dst++    -- Recall that MOV is always a scalar move instruction, but when the destination+    -- is an XMM register, we make the distinction between:+    --+    --  - a scalar format, meaning that from now on we no longer care about the top bits+    --    of the register, and+    --  - a vector format, meaning that we still care about what's in the high bits.+    --+    -- See Note [Allocated register formats] in GHC.CmmToAsm.Reg.Linear.+    MOV dst_fmt src dst       -- MOVSS/MOVSD preserve the upper half of vector registers,       -- but only for reg-2-reg moves-      | VecFormat _ sFmt <- fmt+      | VecFormat _ sFmt <- dst_fmt       , isFloatScalarFormat sFmt       , OpReg {} <- src       , OpReg {} <- dst-      -> usageRM fmt src dst+      -> usageRM dst_fmt src dst       -- other MOV instructions zero any remaining upper part of the destination       -- (largely to avoid partial register stalls)       | otherwise-      -> usageRW fmt src dst+      -> usageRW dst_fmt src dst     MOVD fmt1 fmt2 src dst    ->       -- NB: MOVD and MOVQ always zero any remaining upper part of destination,       -- so the destination is "written" not "modified".@@ -433,7 +445,7 @@     IMUL   fmt src dst    -> usageRM fmt src dst      -- Result of IMULB will be in just in %ax-    IMUL2  II8 src       -> mkRU (mk II8 eax:use_R II8 src []) [mk II8 eax]+    IMUL2  II8 src       -> mkRU (mk II8 eax:use_R II8 src []) [mk II16 eax]     -- Result of IMUL for wider values, will be split between %dx/%edx/%rdx and     -- %ax/%eax/%rax.     IMUL2  fmt src        -> mkRU (mk fmt eax:use_R fmt src []) [mk fmt eax,mk fmt edx]
GHC/CmmToAsm/X86/Ppr.hs view
@@ -35,6 +35,7 @@ import GHC.Cmm.Dataflow.Label import GHC.Cmm.BlockId import GHC.Cmm.CLabel+import GHC.Cmm.InitFini import GHC.Cmm.DebugBlock (pprUnwindTable)  import GHC.Types.Basic (Alignment, mkAlignment, alignmentBytes)@@ -199,8 +200,12 @@         labelInd _ = Nothing   , Just ind' <- labelInd ind   , alias `mayRedirectTo` ind'+  -- See Note [Split sections on COFF objects]+  , not $ platformOS platform == OSMinGW32 && ncgSplitSections config   = pprGloblDecl (ncgPlatform config) alias     $$ line (text ".equiv" <+> pprAsmLabel (ncgPlatform config) alias <> comma <> pprAsmLabel (ncgPlatform config) ind')+    where+      platform = ncgPlatform config  pprDatas config (align, (CmmStaticsRaw lbl dats))  = vcat (pprAlign platform align : pprLabel platform lbl : map (pprData config) dats)@@ -532,9 +537,20 @@ pprSectionAlign :: IsDoc doc => NCGConfig -> Section -> doc pprSectionAlign _config (Section (OtherSection _) _) =      panic "X86.Ppr.pprSectionAlign: unknown section"-pprSectionAlign config sec@(Section seg _) =+pprSectionAlign config sec@(Section seg suffix) =     line (pprSectionHeader config sec) $$+    coffSplitSectionComdatKey $$     pprAlignForSection (ncgPlatform config) seg+  where+    platform = ncgPlatform config+    -- See Note [Split sections on COFF objects]+    coffSplitSectionComdatKey+      | OSMinGW32 <- platformOS platform+      , ncgSplitSections config+      , Nothing <- isInitOrFiniSection seg+      = line (pprCOFFComdatKey platform suffix <> colon)+      | otherwise+      = empty  -- | Print appropriate alignment for the given section type. pprAlignForSection :: IsDoc doc => Platform -> SectionType -> doc
GHC/CmmToC.hs view
@@ -124,7 +124,7 @@     pprDataExterns platform lits $$     pprWordArray platform (isSecConstant section) lbl lits   where-    isSecConstant section = case sectionProtection section of+    isSecConstant (Section t _) = case sectionProtection t of       ReadOnlySection -> True       WriteProtectedSection -> True       _ -> False
GHC/CmmToLlvm.hs view
@@ -217,11 +217,15 @@               Nothing -> [ MetaStr name ]    platform <- getPlatform-  cfg <- getConfig   let stack_alignment_metas =           case platformArch platform of-            ArchX86_64 | llvmCgAvxEnabled cfg -> [mkStackAlignmentMeta 32]-            _                                 -> []+            -- LLVM inserts stack realignment prologue/epilogue when it wants to place __m256 or __m512 on the stack.+            -- However, it reserves %rbp as the frame pointer, conflicting with our use of it.+            -- Therefore, we tell LLVM that the stack is already aligned to avoid stack realignment.+            -- See also Note [Stack Alignment on X86] and https://gitlab.haskell.org/ghc/ghc/-/issues/26595.+            ArchX86    -> [mkStackAlignmentMeta 64]+            ArchX86_64 -> [mkStackAlignmentMeta 64]+            _          -> []   let codel_model_metas =           case platformArch platform of             -- FIXME: We should not rely on LLVM@@ -271,15 +275,23 @@   -- used if we didn't provide these hints. This will generate a   -- definition of the form   ---  --   @llvm.used = appending global [42 x i8*] [i8* bitcast <var> to i8*, ...]+  --   @llvm.compiler.used = appending global [42 x i8*] [i8* bitcast <var> to i8*, ...]   --   -- Which is the LLVM way of protecting them against getting removed.+  --+  -- We used to emit @llvm.used, but it's too strong and results in+  -- SHF_GNU_RETAIN section flag in the object, which prevents linker+  -- gc-sections from working properly for LLVM backend (#26770).+  -- @llvm.compiler.used serves a similar purpose that protects the+  -- variable from being dropped by llc/opt, but it allows linker+  -- gc-sections to work. See+  -- https://llvm.org/docs/LangRef.html#the-llvm-compiler-used-global-variable   ivars <- getUsedVars   let cast x = LMBitc (LMStaticPointer (pVarLift x)) i8Ptr       ty     = LMArray (length ivars) i8Ptr       usedArray = LMStaticArray (map cast ivars) ty       sectName  = Just $ fsLit "llvm.metadata"-      lmUsedVar = LMGlobalVar (fsLit "llvm.used") ty Appending sectName Nothing Constant+      lmUsedVar = LMGlobalVar (fsLit "llvm.compiler.used") ty Appending sectName Nothing Constant       lmUsed    = LMGlobal lmUsedVar (Just usedArray)   if null ivars      then return ()
GHC/CmmToLlvm/Base.hs view
@@ -286,7 +286,7 @@   , envUniqMeta  :: UniqFM Unique MetaId   -- ^ Global metadata nodes   , envFunMap    :: LlvmEnvMap       -- ^ Global functions so far, with type   , envAliases   :: UniqSet LMString -- ^ Globals that we had to alias, see [Llvm Forward References]-  , envUsedVars  :: [LlvmVar]        -- ^ Pointers to be added to llvm.used (see @cmmUsedLlvmGens@)+  , envUsedVars  :: [LlvmVar]        -- ^ Pointers to be added to llvm.compiler.used (see @cmmUsedLlvmGens@)      -- the following get cleared for every function (see @withClearVars@)   , envVarMap    :: LlvmEnvMap       -- ^ Local variables so far, with type
GHC/CmmToLlvm/CodeGen.hs view
@@ -240,13 +240,34 @@     genCallSimpleCast w op dst args genCall (PrimTarget op@(MO_BSwap w)) [dst] args =     genCallSimpleCast w op dst args-genCall (PrimTarget op@(MO_Pdep w)) [dst] args =-    genCallSimpleCast w op dst args-genCall (PrimTarget op@(MO_Pext w)) [dst] args =-    genCallSimpleCast w op dst args genCall (PrimTarget op@(MO_PopCnt w)) [dst] args =     genCallSimpleCast w op dst args+{- Note [LLVM PDep/PExt intrinsics]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+Since x86 PDep/PExt instructions only exist for 32/64 bit widths+we use the 32bit variant to compute the 8/16bit primops.+To do so we extend/truncate the argument/result around the+call. +Note that the 64-bit intrinsics (`llvm.x86.bmi.pdep.64` and+`llvm.x86.bmi.pext.64`) are only legal on 64-bit x86 targets, not on+i386. Therefore on i386 we must fall back to the runtime helper+(`hs_pdep64`/`hs_pext64`) for the 64-bit primops.++See https://github.com/llvm/llvm-project/issues/172857 for upstream+discussion about portable pdep/pext intrinsics.+-}+genCall (PrimTarget op@(MO_Pdep w)) [dst] args = do+    cfg <- getConfig+    if  llvmCgBmiVersion cfg >= Just BMI2+        then genCallMinimumTruncationCast W32 w op dst args+        else genCallSimpleCast w op dst args+genCall (PrimTarget op@(MO_Pext w)) [dst] args = do+    cfg <- getConfig+    if  llvmCgBmiVersion cfg >= Just BMI2+        then genCallMinimumTruncationCast W32 w op dst args+        else genCallSimpleCast w op dst args+ genCall (PrimTarget (MO_AtomicRMW width amop)) [dst] [addr, n] = runStmtsDecls $ do     addrVar <- exprToVarW addr     nVar <- exprToVarW n@@ -641,8 +662,15 @@ -- from i32 to i8 explicitly as LLVM is strict about types. genCallSimpleCast :: Width -> CallishMachOp -> CmmFormal -> [CmmActual]                   -> LlvmM StmtData-genCallSimpleCast specW op dst args = do-    let width   = widthToLlvmInt specW+genCallSimpleCast w = genCallMinimumTruncationCast w w++-- Given the minimum machine bit-width to use and the logical bit-width of the+-- value range, perform a type-cast truncation and extension before and after the+-- specified operation, respectively.+genCallMinimumTruncationCast :: Width -> Width -> CallishMachOp -> CmmFormal+                             -> [CmmActual] -> LlvmM StmtData+genCallMinimumTruncationCast minW specW op dst args = do+    let width   = widthToLlvmInt $ max minW specW         argsW   = const width <$> args         dstType = cmmToLlvmType $ localRegType dst         signage = cmmPrimOpRetValSignage op@@ -945,39 +973,39 @@       W256 -> fsLit "llvm.cttz.i256"       W512 -> fsLit "llvm.cttz.i512"     MO_Pdep w+      -- See Note [LLVM PDep/PExt intrinsics]       | isBmi2Enabled -> case w of-          W8   -> fsLit "llvm.x86.bmi.pdep.8"-          W16  -> fsLit "llvm.x86.bmi.pdep.16"+          W8   -> fsLit "llvm.x86.bmi.pdep.32"+          W16  -> fsLit "llvm.x86.bmi.pdep.32"           W32  -> fsLit "llvm.x86.bmi.pdep.32"-          W64  -> fsLit "llvm.x86.bmi.pdep.64"-          W128 -> fsLit "llvm.x86.bmi.pdep.128"-          W256 -> fsLit "llvm.x86.bmi.pdep.256"-          W512 -> fsLit "llvm.x86.bmi.pdep.512"+          W64+            | is32bit   -> fsLit "hs_pdep64"+            | otherwise -> fsLit "llvm.x86.bmi.pdep.64"+          -- LLVM only provides x86 PDep/PExt intrinsics for 32/64 bits+          _ -> unsupported       | otherwise -> case w of           W8   -> fsLit "hs_pdep8"           W16  -> fsLit "hs_pdep16"           W32  -> fsLit "hs_pdep32"           W64  -> fsLit "hs_pdep64"-          W128 -> fsLit "hs_pdep128"-          W256 -> fsLit "hs_pdep256"-          W512 -> fsLit "hs_pdep512"+          _ -> unsupported     MO_Pext w       | isBmi2Enabled -> case w of-          W8   -> fsLit "llvm.x86.bmi.pext.8"-          W16  -> fsLit "llvm.x86.bmi.pext.16"+          -- See Note [LLVM PDep/PExt intrinsics]+          W8   -> fsLit "llvm.x86.bmi.pext.32"+          W16  -> fsLit "llvm.x86.bmi.pext.32"           W32  -> fsLit "llvm.x86.bmi.pext.32"-          W64  -> fsLit "llvm.x86.bmi.pext.64"-          W128 -> fsLit "llvm.x86.bmi.pext.128"-          W256 -> fsLit "llvm.x86.bmi.pext.256"-          W512 -> fsLit "llvm.x86.bmi.pext.512"+          W64+            | is32bit   -> fsLit "hs_pext64"+            | otherwise -> fsLit "llvm.x86.bmi.pext.64"+          -- LLVM only provides x86 PDep/PExt intrinsics for 32/64 bits+          _ -> unsupported       | otherwise -> case w of           W8   -> fsLit "hs_pext8"           W16  -> fsLit "hs_pext16"           W32  -> fsLit "hs_pext32"           W64  -> fsLit "hs_pext64"-          W128 -> fsLit "hs_pext128"-          W256 -> fsLit "hs_pext256"-          W512 -> fsLit "hs_pext512"+          _ -> unsupported      MO_AddIntC w    -> case w of       W8   -> fsLit "llvm.sadd.with.overflow.i8"
GHC/CmmToLlvm/Config.hs view
@@ -22,7 +22,6 @@   , llvmCgContext           :: !SDocContext  -- ^ Context for LLVM code generation   , llvmCgFillUndefWithGarbage :: !Bool      -- ^ Fill undefined literals with garbage values   , llvmCgSplitSection      :: !Bool         -- ^ Split sections-  , llvmCgAvxEnabled        :: !Bool   , llvmCgBmiVersion        :: Maybe BmiVersion  -- ^ (x86) BMI instructions   , llvmCgLlvmVersion       :: Maybe LlvmVersion -- ^ version of Llvm we're using   , llvmCgDoWarn            :: !Bool         -- ^ True ==> warn unsupported Llvm version
GHC/CmmToLlvm/Data.hs view
@@ -75,7 +75,7 @@                 IsFiniArray -> fsLit "llvm.global_dtors"     in genGlobalLabelArray var clbls -genLlvmData (sec, CmmStaticsRaw lbl xs) = do+genLlvmData (sec@(Section t _), CmmStaticsRaw lbl xs) = do     label <- strCLabel_llvm lbl     static <- mapM genData xs     lmsec <- llvmSection sec@@ -92,7 +92,7 @@                                                     then Just 2 else Just 1                             Section Data _    -> Just $ platformWordSizeInBytes platform                             _                 -> Nothing-        const          = if sectionProtection sec == ReadOnlySection+        const          = if sectionProtection t == ReadOnlySection                             then Constant else Global         varDef         = LMGlobalVar label tyAlias link lmsec align const         globDef        = LMGlobal varDef struct
GHC/CmmToLlvm/Mangler.hs view
@@ -38,7 +38,7 @@  -- | These are the rewrites that the mangler will perform rewrites :: [Rewrite]-rewrites = [rewriteSymType, rewriteAVX, rewriteCall, rewriteJump]+rewrites = [rewriteSymType, rewriteCall, rewriteJump]  type Rewrite = Platform -> B.ByteString -> Maybe B.ByteString @@ -84,23 +84,6 @@       where         funcType = prefix `B.cons` B.pack "function"         objType  = prefix `B.cons` B.pack "object"---- | This rewrites aligned AVX instructions to their unaligned counterparts on--- x86-64. This is necessary because the stack is not adequately aligned for--- aligned AVX spills, so LLVM would emit code that adjusts the stack pointer--- and disable tail call optimization. Both would be catastrophic here so GHC--- tells LLVM that the stack is 32-byte aligned (even though it isn't) and then--- rewrites the instructions in the mangler.-rewriteAVX :: Rewrite-rewriteAVX platform s-  | not isX86_64 = Nothing-  | isVmovdqa s  = Just $ replaceOnce (B.pack "vmovdqa") (B.pack "vmovdqu") s-  | isVmovap s   = Just $ replaceOnce (B.pack "vmovap") (B.pack "vmovup") s-  | otherwise    = Nothing-  where-    isX86_64 = platformArch platform == ArchX86_64-    isVmovdqa = B.isPrefixOf (B.pack "vmovdqa")-    isVmovap = B.isPrefixOf (B.pack "vmovap")  -- | This rewrites (tail) calls to avoid creating PLT entries for -- functions on riscv64. The replacement will load the address from the
GHC/CmmToLlvm/Version/Bounds.hs view
@@ -16,4 +16,4 @@  -- | The (not-inclusive) upper bound  bound on the LLVM Version that is currently supported. supportedLlvmVersionUpperBound :: LlvmVersion-supportedLlvmVersionUpperBound = LlvmVersion (21 NE.:| [])+supportedLlvmVersionUpperBound = LlvmVersion (24 NE.:| [])
GHC/Core.hs view
@@ -284,7 +284,9 @@ -- See Note [GHC Formalism] in GHC.Core.Lint data AltCon   = DataAlt DataCon   --  ^ A plain data constructor: @case e of { Foo x -> ... }@.-                      -- Invariant: the 'DataCon' is always from a @data@ type, and never from a @newtype@+                      -- Invariant: the 'DataCon' is always from a @data@ type,+                      -- and never from a @newtype@ or a unary class.+                      -- See Note [DataAlt restrictions]    | LitAlt  Literal   -- ^ A literal: @case e of { 1 -> ... }@                       -- Invariant: always an *unlifted* literal@@ -328,6 +330,63 @@ mkBinds NonRecursive binds = map (uncurry NonRec) binds  {-+Note [DataAlt restrictions]+~~~~~~~~~~~~~~~~~~~~~~~~~~~+The DataCon in a DataAlt is subject to three restrictions:++(DALT1) It is never from a newtype.++  Newtypes are always represented via coercions, never by pattern matching+  on their data constructor. We can still have a case expression over a+  newtype scrutinee if we are just doing an eval:++      case x of { DEFAULT -> e }++  but we must not match on the newtype constructor.++(DALT2) It is never from a `type data` declaration.++  The constructors of a `type data` declaration (see+  Note [Type data declarations] in GHC.Rename.Module) exist only at the+  type level and have no value-level representation. Nevertheless, it is+  possible to strictly evaluate a value whose type is a `type data`+  declaration. For example (from test type-data/should_compile/T2294b.hs):++      type data T a where+        A :: T Int++      f :: T a -> ()+      f !x = ()++  We want to generate the following Core for f:++      f = \(@a) (x :: T a) ->+          case x of { __DEFAULT -> () }++  Namely we do _not_ want to match on `A`, as it doesn't exist at the value+  level! See wrinkle (W2b) in Note [Type data declarations] in+  GHC.Rename.Module.++(DALT3) It is never from a unary class (#27071).++  Unary class constructors are erased at runtime: the dictionary IS the+  single method (or superclass), with no wrapper. Matching on the dictionary+  constructor is therefore illegal in Core; case expressions over unary+  class dictionaries must use DEFAULT. For example, given++      class C a where { op :: a -> a }++  a case on a C dictionary looks like:++      case d of bndr { DEFAULT -> ...bndr... }+  not:+      case d of { C:C op -> ...op... }    -- WRONG++  See (UCM13) in Note [Unary class magic] in GHC.Core.TyCon.++All three restrictions are checked by Core Lint, and they each give rise+to a special case in `GHC.Core.Utils.refineDefaultAlt`.+ Note [Literal alternatives] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Literal alternatives (LitAlt lit) are always for *un-lifted* literals.@@ -524,7 +583,9 @@ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It is a global invariant (not checkable by Lint) that -     every non-newtype dictionary-typed expression is non-bottom.+  Every dictionary-typed expression is non-bottom+  /except/: a unary class with a single field, either a single method,+            or a single superclass: see (NBD1).  These conditions are captured by GHC.Core.Type.isTerminatingType. @@ -535,7 +596,7 @@   See DFunUnfolding in GHC.Core.  So the result of a call to a DFun is always   non-bottom. -  Exception: newtype dictionaries.+  Exception: unary dictionaries: see (NBD1) below.    Plus: see the Very Nasty Wrinkle in Note [Speculative evaluation]   in GHC.CoreToStg.Prep@@ -558,6 +619,35 @@    can be discarded by the Simplifier.  See these Notes:    Note [exprOkForSpeculation and type classes] in GHC.Core.Utils    Note[Speculative evaluation] in GHC.CoreToStg.Prep++Wrinkle (NBD1)+  A unary dictionary with a single method can be non-bottom:+     class UC a where { meth :: a -> a }+  because we could say+     instance UC Int where { meth = error "urk" }+  See Note [Unary class magic] in GHC.Core.TyCon++  A unary class has a single /superclass/ (rather than method) looks as if it+  will always terminate, because the superclass does:+    class C a => UC a where {}+  So we could try to be more clever, and say that a unary class constraint+  always terminates if has a single superclass.++  But maybe that is too clever!  Note [Recursive superclasses] and+  Note [Solving superclass constraints] are very subtle, so it seems safer to+  say that /all/ unary-class constraints might diverge.  Remember, almost all+  classes are non-unary, and thus definitely non-bottom.++Wrinkle (NBD2)+  A class declared in an hs-boot file is an AbstractTyCon inside the module+  loop:+      module Callee where { class UC (a :: Type) }                -- Callee.hs-boot+      module Callee where { class UC a where { ucm :: a -> a } }  -- Callee.hs+  isUnaryClassTyCon returns False for it, but compiling the real declaration+  may reveal a UnaryClassTyCon, whose dictionary is `ucm` and can be bottom.++  Speculating a superclass selection from such a dictionary crashes (#27704).+  So we must treat an AbstractTyCon as possibly unary.  Note [Case expression invariants] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
GHC/Core/Lint.hs view
@@ -1725,11 +1725,13 @@     lit_ty = literalType lit  lintCoreAlt case_bndr scrut_ty _scrut_mult alt_ty alt@(Alt (DataAlt con) args rhs)-  | isNewTyCon (dataConTyCon con)+  | isNewTyCon (dataConTyCon con)            -- (DALT1) in Note [DataAlt restrictions] in GHC.Core   = zeroUE <$ addErrL (mkNewTyDataConAltMsg scrut_ty alt)+  | isUnaryClassTyCon (dataConTyCon con)     -- (DALT3) in Note [DataAlt restrictions] in GHC.Core+  = zeroUE <$ addErrL (mkUnaryClassDataConAltMsg scrut_ty alt)   | Just (tycon, tycon_arg_tys) <- splitTyConApp_maybe scrut_ty   = addLoc (CaseAlt alt) $  do-    { checkTypeDataConOcc "pattern" con+    { checkTypeDataConOcc "pattern" con      -- (DALT2) in Note [DataAlt restrictions] in GHC.Core     ; lintL (tycon == dataConTyCon con) (mkBadConMsg tycon con)        -- Instantiate the universally quantified@@ -3784,6 +3786,11 @@            text "Scrutinee type:" <+> ppr scrut_ty,            text "Alternative:" <+> pprCoreAlt alt ] +mkUnaryClassDataConAltMsg :: Type -> CoreAlt -> SDoc+mkUnaryClassDataConAltMsg scrut_ty alt+  = vcat [ text "Data alternative for unary class datacon"+         , text "Scrutinee type:" <+> ppr scrut_ty+         , text "Alternative:" <+> pprCoreAlt alt ]  ------------------------------------------------------ --      Other error messages
GHC/Core/Make.hs view
@@ -235,13 +235,16 @@ -- Fail (returning Nothing) if --    * the RuntimeRep of the Type is not monomorphic; --    * the type is (a ~# b), the type of coercion--- See INVARIANT 1 and 2 of item (2) in Note [Rubbish literals]+--    * the type is terminating (isTerminatingType), e.g. a dictionary+-- See INVARIANT 1, 2 and 3 of item (2) in Note [Rubbish literals] -- in GHC.Types.Literal mkLitRubbish ty   | not (noFreeVarsOfType rep)   = Nothing   -- Satisfy INVARIANT 1   | isEqPred ty   = Nothing   -- Satisfy INVARIANT 2+  | isTerminatingType ty+  = Nothing   -- Satisfy INVARIANT 3   | otherwise   = Just (Lit (LitRubbish torc rep) `mkTyApps` [ty])   where
GHC/Core/Map/Type.hs view
@@ -47,7 +47,7 @@ import GHC.Types.Name.Env import GHC.Types.Var import GHC.Types.Var.Env-import GHC.Types.Unique.FM+import GHC.Types.Unique.DFM import GHC.Utils.Outputable  import GHC.Utils.Panic@@ -367,14 +367,14 @@  ------------------------ data TyLitMap a = TLM { tlm_number :: Map.Map Integer a-                      , tlm_string :: UniqFM  FastString a+                      , tlm_string :: UniqDFM  FastString a                       , tlm_char   :: Map.Map Char a                       }  -- TODO(22292): derive instance Functor TyLitMap where     fmap f TLM { tlm_number = tn, tlm_string = ts, tlm_char = tc } = TLM-      { tlm_number = Map.map f tn, tlm_string = mapUFM f ts, tlm_char = Map.map f tc }+      { tlm_number = Map.map f tn, tlm_string = mapUDFM f ts, tlm_char = Map.map f tc }  instance TrieMap TyLitMap where    type Key TyLitMap = TyLit@@ -386,34 +386,34 @@    mapMaybeTM = mpTyLit  emptyTyLitMap :: TyLitMap a-emptyTyLitMap = TLM { tlm_number = Map.empty, tlm_string = emptyUFM, tlm_char = Map.empty }+emptyTyLitMap = TLM { tlm_number = Map.empty, tlm_string = emptyUDFM, tlm_char = Map.empty }  lkTyLit :: TyLit -> TyLitMap a -> Maybe a lkTyLit l =   case l of     NumTyLit n -> tlm_number >.> Map.lookup n-    StrTyLit n -> tlm_string >.> (`lookupUFM` n)+    StrTyLit n -> tlm_string >.> (`lookupUDFM` n)     CharTyLit n -> tlm_char >.> Map.lookup n  xtTyLit :: TyLit -> XT a -> TyLitMap a -> TyLitMap a xtTyLit l f m =   case l of     NumTyLit n ->  m { tlm_number = Map.alter f n (tlm_number m) }-    StrTyLit n ->  m { tlm_string = alterUFM  f (tlm_string m) n }+    StrTyLit n ->  m { tlm_string = alterUDFM  f (tlm_string m) n }     CharTyLit n -> m { tlm_char = Map.alter f n (tlm_char m) }  foldTyLit :: (a -> b -> b) -> TyLitMap a -> b -> b-foldTyLit l m = flip (nonDetFoldUFM l) (tlm_string m)+foldTyLit l m = flip (foldUDFM l)  (tlm_string m)               . flip (Map.foldr l) (tlm_number m)               . flip (Map.foldr l) (tlm_char m)  filterTyLit :: (a -> Bool) -> TyLitMap a -> TyLitMap a filterTyLit f (TLM { tlm_number = tn, tlm_string = ts, tlm_char = tc })-  = TLM { tlm_number = Map.filter f tn, tlm_string = filterUFM f ts, tlm_char = Map.filter f tc }+  = TLM { tlm_number = Map.filter f tn, tlm_string = filterUDFM f ts, tlm_char = Map.filter f tc }  mpTyLit :: (a -> Maybe b) -> TyLitMap a -> TyLitMap b mpTyLit f (TLM { tlm_number = tn, tlm_string = ts, tlm_char = tc })-  = TLM { tlm_number = Map.mapMaybe f tn, tlm_string = mapMaybeUFM f ts, tlm_char = Map.mapMaybe f tc }+  = TLM { tlm_number = Map.mapMaybe f tn, tlm_string = mapMaybeUDFM f ts, tlm_char = Map.mapMaybe f tc }  ------------------------------------------------- -- | @TypeMap a@ is a map from 'Type' to @a@.  If you are a client, this
GHC/Core/Opt/Arity.hs view
@@ -2080,7 +2080,11 @@           (expr', args) = collectArgs expr           (ticks, expr'') = stripTicksTop tickishFloatable expr'           sexpr = mkApps expr'' args-          retick expr = foldr mkTick expr ticks+          retick expr = foldr mkTickCpe expr ticks+            -- Defensive programming: use 'mkTickCpe' instead of 'mkTick',+            -- as this code can be called by Core Prep.+            --+            -- See Note [mkTick breaks ANF] in GHC.CoreToStg.Prep  {- ********************************************************************* *                                                                      *
GHC/Core/Opt/DmdAnal.hs view
@@ -23,7 +23,7 @@ import GHC.Core.Utils import GHC.Core.TyCon import GHC.Core.Type-import GHC.Core.FVs      ( rulesRhsFreeIds, bndrRuleAndUnfoldingIds )+import GHC.Core.FVs      ( rulesRhsFreeIds, bndrRuleAndUnfoldingIds, idRuleVars ) import GHC.Core.Coercion ( Coercion ) import GHC.Core.TyCo.FVs     ( coVarsOfCos ) import GHC.Core.TyCo.Compare ( eqType )@@ -1105,10 +1105,23 @@     rhs_sd = mkCalledOnceDmds ww_arity adjusted_body_sd      WithDmdType rhs_dmd_ty rhs' = dmdAnal env rhs_sd rhs-    DmdType rhs_env rhs_dmds = rhs_dmd_ty-    (final_rhs_dmds, final_rhs) = finaliseArgBoxities env id ww_arity-                                                      rhs_dmds (de_div rhs_env) rhs' +    -- See Note [Absence analysis for stable unfoldings and RULES], Wrinkle (W3)+    full_dmd_ty = addUnfoldingDemands env rhs_sd id rhs_dmd_ty+    DmdType full_rhs_env combined_rhs_dmds = full_dmd_ty++    final_rhs_dmds = finaliseArgBoxities env id ww_arity+                                         combined_rhs_dmds (de_div full_rhs_env) rhs'++    -- Attach the final demands to the lambda binders of the RHS.+    -- IMPORTANT: The lambda binders of final_rhs must carry the final demand+    -- info, because worker/wrapper drives decisions from the idDemandInfo on+    -- the lambdas (see mkWwstr_one), NOT from the strictness signature of the+    -- function. So the demands must reflect both the unfolding combination+    -- (from addUnfoldingDemands) and the boxity finalisation (from+    -- finaliseArgBoxities).+    final_rhs = setLamDmds final_rhs_dmds rhs'+     dmd_sig_arity = ww_arity + strictCallArity body_sd     sig = mkDmdSigForArity dmd_sig_arity (DmdType sig_env final_rhs_dmds)           -- strictCallArity is > 0 only for join points@@ -1131,19 +1144,51 @@     --        we never get used-once info for FVs of recursive functions.     --        See #14816 where we try to get rid of reuseEnv.     rhs_env1 = case rec_flag of-                Recursive    -> reuseEnv rhs_env-                NonRecursive -> rhs_env+                Recursive    -> reuseEnv full_rhs_env+                NonRecursive -> full_rhs_env      -- See Note [Absence analysis for stable unfoldings and RULES]-    rhs_env2 = rhs_env1 `plusDmdEnv` demandRootSet env (bndrRuleAndUnfoldingIds id)+    -- The unfolding FVs are already included in full_rhs_env via addUnfoldingDemands.+    -- Here we only need demandRoots for RULES.+    rhs_env2 = rhs_env1 `plusDmdEnv` demandRootSet env (filterVarSet isId (idRuleVars id))      -- See Note [Lazy and unleashable free variables]     !(!sig_env, !weak_fvs) = splitWeakDmds rhs_env2 +setLamDmds :: [Demand] -> CoreExpr -> CoreExpr+-- Attach the demands to the outer lambdas of this expression+setLamDmds (dmd:dmds) (Lam v e)+  | isTyVar v = Lam v (setLamDmds (dmd:dmds) e)+  | otherwise = Lam (v `setIdDemandInfo` dmd) (setLamDmds dmds e)+setLamDmds dmds (Cast e co) = Cast (setLamDmds dmds e) co+   -- This case happens for an OPAQUE function, which may look like+   --     f = (\x y. blah) |> co+   -- We give it strictness but no boxity (#22502)+setLamDmds _ e = e+   -- In the OPAQUE case, the list of demands at this point might be+   -- non-empty, e.g., when looking at a PAP. Hence don't panic (#22997).+ splitWeakDmds :: DmdEnv -> (DmdEnv, WeakDmds) splitWeakDmds (DE fvs div) = (DE sig_fvs div, weak_fvs)   where (!weak_fvs, !sig_fvs) = partitionVarEnv isWeakDmd fvs +-- | If there is a stable unfolding, combine argument demands and free variable+-- demands from the unfolding with those from the RHS.+-- See Note [Absence analysis for stable unfoldings and RULES], Wrinkle (W3).+-- See Note [Combining demands for stable unfoldings] in GHC.Types.Demand.+addUnfoldingDemands :: AnalEnv -> SubDemand -> Id -> DmdType -> DmdType+addUnfoldingDemands env rhs_sd id rhs_dmd_ty+  | isStableUnfolding unf+  , Just unf_body <- maybeUnfoldingTemplate unf+  , let WithDmdType unf_dmd_ty _ = dmdAnal env rhs_sd unf_body+  = -- pprTrace "addUnfoldingDemands" (ppr id $$ ppr rhs_dmd_ty $$ ppr unf_dmd_ty) $+    maxDmdType rhs_dmd_ty unf_dmd_ty++  | otherwise+  = rhs_dmd_ty  -- No stable unfolding, nothing to do+  where+    unf = realIdUnfolding id+ -- | The result type after applying 'idArity' many arguments. Returns 'Nothing' -- when the type doesn't have exactly 'idArity' many arrows. resultType_maybe :: Id -> Maybe Type@@ -1481,10 +1526,21 @@  Now if f is subsequently inlined, we'll use 'g' and ... disaster. -SOLUTION: if f has a stable unfolding, treat every free variable as a-/demand root/, that is: Analyse it as if it was a variable occurring in a+SOLUTION for stable unfoldings: in `dmdAnalRhsSig`, if the function has a+stable unfolding, analyse it with `dmdAnal` and combine the resulting `DmdType`+with the RHS's `DmdType`. This is done by `addUnfoldingDemands`, which uses+`maxDmdType` to combine both argument demands and free variable demands.+See Note [Combining demands for stable unfoldings] in GHC.Types.Demand for+details of the combining operation.++This handles both the free variables and arguments of stable unfoldings in one+go. For example, in the scenario above, the unfolding's `DmdType` will mention+`g` as a free variable, so `maxDmdType` will keep it alive.++SOLUTION for RULES: treat every Id free in the RHS of a RULE as a+/demand root/, that is: analyse it as if it was a variable occurring in a 'topDmd' context. This is done in `demandRoot` (which we also use for exported-top-level ids). Do the same for Ids free in the RHS of any RULES for f.+top-level ids).  Wrinkles: @@ -1501,7 +1557,7 @@     this, that actually happened in practice.    (W2) You might wonder why we don't simply take the free vars of the-    unfolding/RULE and map them to topDmd. The reason is that any of the free vars+    RULE and map them to topDmd. The reason is that any of the free vars     might have demand signatures themselves that in turn demand transitive free     variables and that we hence need to unleash! This came up in #23208.     Consider@@ -1523,6 +1579,24 @@     for `sg`, failing to unleash the signature and hence observed an absent     error instead of the `really important message`. +  (W3) The stable unfolding solution above handles /free variables/, but+    what about /arguments/?  Consider (#26416)++       fromVector :: (Storable a, KnownNat n) => Vector a -> Vector a+       fromVector v = ... (uses Storable dictionary) ...+       {-# INLINABLE fromVector #-}++    Suppose that the optimised RHS of `fromVector` somehow discards the use of+    the Storable dictionary, but the stable unfolding still uses it. Then the+    demand signature will say that the Storable dictionary argument is absent,+    and worker/wrapper will replace it with `LitRubbish`.  But when the+    worker's unfolding is inlined, it will use that rubbish value as a real+    dictionary, leading to a segfault!++    `addUnfoldingDemands` handles this too: since `maxDmdType` combines both+    the argument demands and free variable demands from the unfolding's+    `DmdType` with the RHS's, argument absence is correctly prevented.+ Note [DmdAnal for DataCon wrappers] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We give DataCon wrappers a (necessarily flat) demand signature in@@ -2000,22 +2074,20 @@  finaliseArgBoxities :: AnalEnv -> Id -> Arity                     -> [Demand] -> Divergence-                    -> CoreExpr -> ([Demand], CoreExpr)+                    -> CoreExpr -> [Demand] -- POSTCONDITION:--- If:    (dmds', rhs') = finaliseArgBoxitities ... dmds .. rhs+-- If:    dmds' = finaliseArgBoxities ... dmds .. rhs -- Then: --     dmds' is the same as dmds (including length), except for boxity info---     rhs'  is the same as rhs, except for dmd info on lambda binders -- NB: For join points, length dmds might be greater than ww_arity+-- NB: rhs is needed only to count visible binders. finaliseArgBoxities env fn ww_arity arg_dmds div rhs    -- Check for an OPAQUE function: see Note [OPAQUE pragma]   -- In that case, trim off all boxity info from argument demands-  -- and demand info on lambda binders   -- See Note [The OPAQUE pragma and avoiding the reboxing of arguments]   | isOpaquePragma (idInlinePragma fn)-  , let trimmed_arg_dmds = map trimBoxity arg_dmds-  = (trimmed_arg_dmds, set_lam_dmds trimmed_arg_dmds rhs)+  = map trimBoxity arg_dmds    -- Check that we have enough visible binders to match the   -- ww arity; if not, we won't do worker/wrapper@@ -2026,7 +2098,7 @@   -- It's a bit of a corner case.  Anyway for now we pass on the   -- unadulterated demands from the RHS, without any boxity trimming.   | ww_arity > count isId bndrs-  = (arg_dmds, rhs)+  = arg_dmds    -- The normal case   | otherwise@@ -2035,10 +2107,7 @@     --        , text "max" <+> ppr max_wkr_args     --        , text "dmds before:" <+> ppr (map idDemandInfo (filter isId bndrs))     --        , text "dmds after: " <+>  ppr arg_dmds' ]) $-    (arg_dmds', set_lam_dmds arg_dmds' rhs)-    -- set_lam_dmds: we must attach the final boxities to the lambda-binders-    -- of the function, both because that's kosher, and because CPR analysis-    -- uses the info on the binders directly.+    arg_dmds'   where     opts           = ae_opts env     (bndrs, _body) = collectBinders rhs@@ -2046,8 +2115,11 @@      arg_triples :: [(Type, StrictnessMark, Demand)]     arg_triples = take ww_arity $-                  [ (idType bndr, NotMarkedStrict, get_dmd bndr)-                  | bndr <- bndrs, isRuntimeVar bndr ]+                  zipWith mk_triple+                          [ bndr | bndr <- bndrs, isRuntimeVar bndr ]+                          arg_dmds+      where+        mk_triple bndr arg_dmd = (idType bndr, NotMarkedStrict, get_dmd arg_dmd)      arg_dmds' = ww_arg_dmds ++ map trimBoxity (drop ww_arity arg_dmds)                 -- If ww_arity < length arg_dmds, the leftover ones@@ -2063,12 +2135,10 @@                     -- This is the budget initialisation step of                     -- Note [Worker argument budget] -    get_dmd :: Id -> Demand-    get_dmd bndr+    get_dmd :: Demand -> Demand+    get_dmd dmd       | is_bot_fn = unboxDeeplyDmd dmd -- See Note [Boxity for bottoming functions],       | otherwise = dmd                --     case (B)-      where-        dmd = idDemandInfo bndr      -- is_bot_fn:  see Note [Boxity for bottoming functions]     is_bot_fn = div == botDiv@@ -2124,19 +2194,6 @@               ~(final_bg_inner, final_dmd) -- "~": This match *must* be lazy!                  | positiveTopBudget bg_inner' = (bg_inner', dmd')                  | otherwise                   = (bg_inner,  trimBoxity dmd)--    set_lam_dmds :: [Demand] -> CoreExpr -> CoreExpr-    -- Attach the demands to the outer lambdas of this expression-    set_lam_dmds (dmd:dmds) (Lam v e)-      | isTyVar v = Lam v (set_lam_dmds (dmd:dmds) e)-      | otherwise = Lam (v `setIdDemandInfo` dmd) (set_lam_dmds dmds e)-    set_lam_dmds dmds (Cast e co) = Cast (set_lam_dmds dmds e) co-       -- This case happens for an OPAQUE function, which may look like-       --     f = (\x y. blah) |> co-       -- We give it strictness but no boxity (#22502)-    set_lam_dmds _ e = e-       -- In the OPAQUE case, the list of demands at this point might be-       -- non-empty, e.g., when looking at a PAP. Hence don't panic (#22997).  finaliseLetBoxity   :: AnalEnv
GHC/Core/Opt/OccurAnal.hs view
@@ -9,7 +9,9 @@ -- many /other/ arguments the function has.  Inconsistent unboxing is very -- bad for performance, so I increased the limit to allow it to unbox -- consistently.+-- AK: Seems we no longer unbox OccEnv now anyway so it might be redundant. + {- (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 @@ -26,7 +28,7 @@ module GHC.Core.Opt.OccurAnal (     occurAnalysePgm,     occurAnalyseExpr,-    zapLambdaBndrs, BinderSwapDecision(..), scrutOkForBinderSwap+    zapLambdaBndrs   ) where  import GHC.Prelude hiding ( head, init, last, tail )@@ -34,7 +36,7 @@ import GHC.Core import GHC.Core.FVs import GHC.Core.Utils   ( exprIsTrivial, isDefaultAlt, isExpandableApp,-                          mkCastMCo, mkTicks )+                          mkCastMCo, mkTicks, BinderSwapDecision(..), scrutOkForBinderSwap ) import GHC.Core.Opt.Arity   ( joinRhsArity, isOneShotBndr ) import GHC.Core.Coercion import GHC.Core.Type@@ -967,6 +969,12 @@   -> ([CoreBind] -> r -> r)          -- How to combine the scope with new binds   -> WithUsageDetails r              -- Of the whole let(rec) +-- AK: While not allocating any less inlining occAnalBind turns calls to the+-- passed functions into known calls with all the benefits that brings.+-- On a version of T26425 with 6k alternatives this improved compile+-- by 10-20% with -O.+{-# INLINE occAnalBind #-}+ occAnalBind env lvl ire (Rec pairs) thing_inside combine   = addInScopeList env (map fst pairs) $ \env ->     let WUD body_uds body'  = thing_inside env@@ -984,7 +992,7 @@   = -- Analyse the RHS and /then/ the body     let -- Analyse the rhs first, generating rhs_uds         !(rhs_uds_s, bndr', rhs') = occAnalNonRecRhs env lvl ire mb_join bndr rhs-        rhs_uds = foldr1 orUDs rhs_uds_s   -- NB: orUDs.  See (W4) of+        rhs_uds = foldl1' orUDs rhs_uds_s   -- NB: orUDs.  See (W4) of                                            -- Note [Occurrence analysis for join points]          -- Now analyse the body, adding the join point@@ -1049,6 +1057,7 @@     -- Match join arity O from mb_join_arity with manifest join arity M as     -- returned by of occAnalLamTail. It's totally OK for them to mismatch;     -- hence adjust the UDs from the RHS+     WUD adj_rhs_uds final_rhs = adjustNonRecRhs mb_join $                                 occAnalLamTail rhs_env rhs     final_bndr_with_rules@@ -1341,16 +1350,17 @@ That is the whole reason for computing rule_fv_env in mkLoopBreakerNodes. Wrinkles: -* We only consider /active/ rules. See Note [Finding rule RHS free vars]+(RLB1) We only consider /active/ rules.+  This is important: see Note [Finding rule RHS free vars] -* We need only consider free vars that are also binders in this Rec+(RLB2) We need only consider free vars that are also binders in this Rec   group.  See also Note [Finding rule RHS free vars] -* We only consider variables free in the *RHS* of the rule, in+(RLB3) We only consider variables free in the *RHS* of the rule, in   contrast to the way we build the Rec group in the first place (Note   [Rule dependency info]) -* Why "transitive sequence of rules"?  Because active rules apply+(RLB4) Why "transitive sequence of rules"?  Because active rules apply   unconditionally, without checking loop-breaker-ness.  See Note [Loop breaker dependencies]. @@ -1778,10 +1788,13 @@     add_rule_uds (_, l, r) uds = l `andUDs` r `andUDs` uds      -------- active_rule_fvs ------------+    -- See Note [Rules and loop breakers]     active_rule_fvs = foldr add_active_rule imp_rule_fvs rules_w_uds     add_active_rule (rule, _, rhs_uds) fvs-      | is_active (ruleActivation rule)+      | is_active (ruleActivation rule)  -- See (RLB1)       = udFreeVars bndr_set rhs_uds `unionVarSet` fvs+        -- Only consider the `rhs_uss`, not the LHS ones; see (RLB3)+        -- udFreeVars restricts to bndr_set; see (RLB2)       | otherwise       = fvs @@ -2054,6 +2067,18 @@    was a loop breaker last time round  Hence the is_lb field of NodeScore++Note [Strictness in the occurrence analyser]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+By carefully making the occurrence analyser strict in some places, we can+dramatically reduce its memory residency. Among other things we:+* Evaluate the result of `tagLamBinder` and friends, so that the binder (or its+  OccInfo) does not retain the entire `UsageDetails`.  Also use `strictMap` in `tagLamBinders`.+* In `combineUsageDetailsWith`, the fields of the data constructor are strict, and we use+  `strictPlusVarEnv` on the maps that are bound to be needed later on to avoid thunks being+  stored in the values.++These measures reduced residency for test T26425 by a factor of at least 5x. -}  {- *********************************************************************@@ -2188,7 +2213,9 @@     go env rev_bndrs body       = addInScope env rev_bndrs $ \env ->         let !(WUD usage body') = occ_anal_lam_tail env body-            wrap_lam body bndr = Lam (tagLamBinder usage bndr) body+            -- See Note [Strictness in the occurrence analyser]+            wrap_lam !body !bndr = let !bndr' = tagLamBinder usage bndr+                                   in Lam bndr' body         in WUD (usage `addLamCoVarOccs` rev_bndrs)                (foldl' wrap_lam body' rev_bndrs) @@ -2541,7 +2568,8 @@            let alt_env = addBndrSwap scrut' bndr $                          setTailCtxt env  -- Kill off OccRhs                WUD alts_usage alts' = do_alts alt_env alts-               tagged_bndr = tagLamBinder alts_usage bndr+               !tagged_bndr = tagLamBinder alts_usage bndr+               -- See Note [Strictness in the occurrence analyser]            in WUD alts_usage (tagged_bndr, alts')        total_usage = markAllNonTail scrut_usage `andUDs` alts_usage@@ -2559,11 +2587,13 @@     do_alt !env (Alt con bndrs rhs)       = addInScopeList env bndrs $ \ env ->         let WUD rhs_usage rhs' = occAnal env rhs-            tagged_bndrs = tagLamBinders rhs_usage bndrs+            !tagged_bndrs = tagLamBinders rhs_usage bndrs+                           -- See Note [Strictness in the occurrence analyser]         in                 -- See Note [Binders in case alternatives]         WUD rhs_usage (Alt con tagged_bndrs rhs')  occAnal env (Let bind body)+  -- TODO: Would be nice to use a strict version of mkLets here   = occAnalBind env NotTopLevel noImpRuleEdges bind                 (\env -> occAnal env body) mkLets @@ -2644,10 +2674,12 @@   | fun `hasKey` runRWKey   , [t1, t2, arg]  <- args   , WUD usage arg' <- adjustNonRecRhs (JoinPoint 1) $ occAnalLamTail env arg-  = WUD usage (mkTicks ticks $ mkApps (Var fun) [t1, t2, arg'])+  = let app_out = mkTicks ticks $ mkApps (Var fun) [t1, t2, arg']+    in WUD usage app_out  occAnalApp env (Var fun_id, args, ticks)-  = WUD all_uds (mkTicks ticks app')+  = let app_out = mkTicks ticks app'+    in WUD all_uds app_out   where     -- Lots of banged bindings: this is a very heavily bit of code,     -- so it pays not to make lots of thunks here, all of which@@ -2692,8 +2724,9 @@         -- See Note [Sources of one-shot information], bullet point A']  occAnalApp env (fun, args, ticks)-  = WUD (markAllNonTail (fun_uds `andUDs` args_uds))-                     (mkTicks ticks app')+  = let app_out = mkTicks ticks app'+    in WUD (markAllNonTail (fun_uds `andUDs` args_uds)) app_out+   where     !(WUD args_uds app') = occAnalArgs env fun' args []     !(WUD fun_uds fun')  = occAnal (addAppCtxt env args) fun@@ -3417,6 +3450,7 @@ -}  addBndrSwap :: OutExpr -> Id -> OccEnv -> OccEnv+-- See Note [Binder swap] -- See Note [The binder-swap substitution] addBndrSwap scrut case_bndr             env@(OccEnv { occ_bs_env = swap_env, occ_bs_rng = rng_vars })@@ -3424,7 +3458,7 @@   , scrut_var /= case_bndr       -- Consider: case x of x { ... }       -- Do not add [x :-> x] to occ_bs_env, else lookupBndrSwap will loop-  = env { occ_bs_env = extendVarEnv swap_env scrut_var (case_bndr', mco)+  = env { occ_bs_env = extendVarEnv swap_env scrut_var (case_bndr', mkSymMCo mco)         , occ_bs_rng = rng_vars `extendVarSet` case_bndr'                        `unionVarSet` tyCoVarsOfMCo mco } @@ -3434,27 +3468,6 @@     case_bndr' = zapIdOccInfo case_bndr                  -- See Note [Zap case binders in proxy bindings] --- | See bBinderSwaOk.-data BinderSwapDecision-  = NoBinderSwap-  | DoBinderSwap OutVar MCoercion--scrutOkForBinderSwap :: OutExpr -> BinderSwapDecision--- If (scrutOkForBinderSwap e = DoBinderSwap v mco, then---    v = e |> mco--- See Note [Case of cast]--- See Historical Note [Care with binder-swap on dictionaries]------ We use this same function in SpecConstr, and Simplify.Iteration,--- when something binder-swap-like is happening-scrutOkForBinderSwap e-  = case e of-      Tick _ e        -> scrutOkForBinderSwap e  -- Drop ticks-      Var v           -> DoBinderSwap v MRefl-      Cast (Var v) co -> DoBinderSwap v (MCo (mkSymCo co))-                         -- Cast: see Note [Case of cast]-      _               -> NoBinderSwap- lookupBndrSwap :: OccEnv -> Id -> (CoreExpr, Id) -- See Note [The binder-swap substitution] -- Returns an expression of the same type as Id@@ -3650,8 +3663,8 @@ ------------------- -- UsageDetails API -andUDs, orUDs-        :: UsageDetails -> UsageDetails -> UsageDetails+andUDs:: UsageDetails -> UsageDetails -> UsageDetails+orUDs :: UsageDetails -> UsageDetails -> UsageDetails andUDs = combineUsageDetailsWith andLocalOcc orUDs  = combineUsageDetailsWith orLocalOcc @@ -3766,10 +3779,13 @@   | isEmptyVarEnv env1 = uds2   | isEmptyVarEnv env2 = uds1   | otherwise-  = UD { ud_env       = plusVarEnv_C plus_occ_info env1 env2-       , ud_z_many    = plusVarEnv z_many1   z_many2+  -- See Note [Strictness in the occurrence analyser]+  -- Using strictPlusVarEnv here speeds up the test T26425 by about 10% by avoiding+  -- intermediate thunks.+  = UD { ud_env       = strictPlusVarEnv_C plus_occ_info env1 env2+       , ud_z_many    = strictPlusVarEnv z_many1   z_many2        , ud_z_in_lam  = plusVarEnv z_in_lam1 z_in_lam2-       , ud_z_tail    = plusVarEnv z_tail1   z_tail2 }+       , ud_z_tail    = strictPlusVarEnv z_tail1   z_tail2 }  lookupLetOccInfo :: UsageDetails -> Id -> OccInfo -- Don't use locally-generated occ_info for exported (visible-elsewhere)@@ -3847,7 +3863,8 @@               -> [Id]                -- Binders               -> [IdWithOccInfo]     -- Tagged binders tagLamBinders usage binders-  = map (tagLamBinder usage) binders+  -- See Note [Strictness in the occurrence analyser]+  = strictMap (tagLamBinder usage) binders  tagLamBinder :: UsageDetails       -- Of scope              -> Id                 -- Binder@@ -3856,6 +3873,7 @@ -- No-op on TyVars -- A lambda binder never has an unfolding, so no need to look for that tagLamBinder usage bndr+  -- See Note [Strictness in the occurrence analyser]   = setBinderOcc (markNonTail occ) bndr       -- markNonTail: don't try to make an argument into a join point   where
GHC/Core/Opt/Pipeline/Types.hs view
@@ -10,7 +10,7 @@ import GHC.Core.Opt.Monad ( CoreM, FloatOutSwitches ) import GHC.Core.Opt.Simplify ( SimplifyOpts(..) ) -import GHC.Types.Basic  ( CompilerPhase(..) )+import GHC.Types.Basic  ( CompilerPhase ) import GHC.Unit.Module.ModGuts import GHC.Utils.Outputable as Outputable @@ -52,8 +52,8 @@   | CoreDoSpecialising   | CoreDoSpecConstr   | CoreCSE-  | CoreDoRuleCheck CompilerPhase String   -- Check for non-application of rules-                                           -- matching this string+  | CoreDoRuleCheck CompilerPhase String  -- Check for non-application of rules+                                       -- matching this string   | CoreDoNothing                -- Useful when building up   | CoreDoPasses [CoreToDo]      -- lists of these things 
GHC/Core/Opt/SetLevels.hs view
@@ -91,6 +91,7 @@ import GHC.Core.Opt.Arity   ( exprBotStrictness_maybe, isOneShotBndr ) import GHC.Core.FVs     -- all of it import GHC.Core.Subst+import GHC.Core.TyCo.Subst( lookupTyVar ) import GHC.Core.Make    ( sortQuantVars ) import GHC.Core.Type    ( Type, tyCoVarsOfType                         , mightBeUnliftedType, closeOverKindsDSet@@ -466,8 +467,8 @@     ty' = substTyUnchecked (le_subst env) ty      incd_lvl = incMinorLvl (le_ctxt_lvl env)-    dest_lvl = maxFvLevel (const True) env scrut_fvs-            -- Don't abstract over type variables, hence const True+    dest_lvl = maxFvLevel includeTyVars env scrut_fvs+            -- Don't abstract over type variables, hence includeTyVars      lvl_alt alts_env (AnnAlt con bs rhs)       = do { rhs' <- lvlMFE new_env True rhs@@ -719,9 +720,12 @@ -- (In the latter case it won't be a join point any more.) -- Not treating top-level ones specially had a massive effect -- on nofib/minimax/Prog.prog-hasFreeJoin env fvs-  = not (maxFvLevel isJoinId env fvs == tOP_LEVEL)+hasFreeJoin env fvs = anyDVarSet bad_join fvs+  where+    bad_join v = isJoinId v &&+                 maxIn True env v tOP_LEVEL /= tOP_LEVEL + {- Note [Saving work] ~~~~~~~~~~~~~~~~~~~~~ The key idea in let-floating is to@@ -1607,10 +1611,10 @@    | otherwise = max_fv_id_level   where-    max_fv_id_level = maxFvLevel isId env fvs -- Max over Ids only; the-                                              -- tyvars will be abstracted+    max_fv_id_level = maxFvLevel idsOnly env fvs -- Max over Ids only; the+                                                 -- tyvars will be abstracted -    as_far_as_poss = maxFvLevel' isId env fvs_ty+    as_far_as_poss = maxFvLevel' idsOnly env fvs_ty                      -- See Note [Floating and kind casts]  {- Note [Floating and kind casts]@@ -1768,28 +1772,47 @@        , le_env     = add_id id_env (case_bndr, scrut_var) } extendCaseBndrEnv env _ _ = env -maxFvLevel :: (Var -> Bool) -> LevelEnv -> DVarSet -> Level-maxFvLevel max_me env var_set-  = nonDetStrictFoldDVarSet (maxIn max_me env) tOP_LEVEL var_set+includeTyVars, idsOnly :: Bool+idsOnly       = False+includeTyVars = True++maxFvLevel :: Bool -> LevelEnv -> DVarSet -> Level+maxFvLevel include_tyvars env var_set+  = nonDetStrictFoldDVarSet (maxIn include_tyvars env) tOP_LEVEL var_set     -- It's OK to use a non-deterministic fold here because maxIn commutes. -maxFvLevel' :: (Var -> Bool) -> LevelEnv -> TyCoVarSet -> Level+maxFvLevel' :: Bool -> LevelEnv -> TyCoVarSet -> Level -- Same but for TyCoVarSet-maxFvLevel' max_me env var_set-  = nonDetStrictFoldUniqSet (maxIn max_me env) tOP_LEVEL var_set+maxFvLevel' include_tyvars env var_set+  = nonDetStrictFoldUniqSet (maxIn include_tyvars env) tOP_LEVEL var_set     -- It's OK to use a non-deterministic fold here because maxIn commutes. -maxIn :: (Var -> Bool) -> LevelEnv -> InVar -> Level -> Level-maxIn max_me (LE { le_lvl_env = lvl_env, le_env = id_env }) in_var lvl+maxIn :: Bool -> LevelEnv -> InVar -> Level -> Level+-- True <=> include tyvars+maxIn include_tyvars env@(LE { le_subst = subst, le_env = id_env }) in_var lvl+  | isId in_var   = case lookupVarEnv id_env in_var of+      Nothing            -> maxOut env in_var lvl       Just (abs_vars, _) -> foldr max_out lvl abs_vars-      Nothing            -> max_out in_var lvl-  where-    max_out out_var lvl-        | max_me out_var = case lookupVarEnv lvl_env out_var of-                                Just lvl' -> maxLvl lvl' lvl-                                Nothing   -> lvl-        | otherwise = lvl       -- Ignore some vars depending on max_me+          where+            max_out out_var lvl+              | isTyVar out_var && not include_tyvars+                          = lvl+              | otherwise = maxOut env out_var lvl++  | include_tyvars -- TyVars+  = case lookupTyVar subst in_var of+      Just ty -> nonDetStrictFoldVarSet (maxOut env) lvl (tyCoVarsOfType ty)+      Nothing -> maxOut env in_var lvl++  | otherwise      -- Ignore free tyvars+  = lvl++maxOut :: LevelEnv -> OutVar -> Level -> Level+maxOut (LE { le_lvl_env = lvl_env }) out_var lvl+  = case lookupVarEnv lvl_env out_var of+       Just lvl' -> maxLvl lvl' lvl+       Nothing   -> lvl  lookupVar :: LevelEnv -> Id -> LevelledExpr lookupVar le v = case lookupVarEnv (le_env le) v of
GHC/Core/Opt/Simplify/Env.hs view
@@ -12,6 +12,7 @@          -- * Environments         SimplEnv(..), pprSimplEnv,   -- Temp not abstract+        SimplPhase(..), isActive, simplStartPhase, simplEndPhase,         seArityOpts, seCaseCase, seCaseFolding, seCaseMerge, seCastSwizzle,         seDoEtaReduction, seEtaExpand, seFloatEnable, seInline, seNames,         seOptCoercionOpts, sePhase, sePlatform, sePreInline,@@ -145,7 +146,7 @@ Note that it doesn't matter for the decision procedure wheter a value is altered throughout an iteration of the Simplify pass: The fields sm_phase, sm_inline, sm_rules, sm_cast_swizzle and sm_eta_expand are updated locally (See the-definitions of `updModeForStableUnfoldings` and `updModeForRules` in+definitions of `updModeForStableUnfoldings` and `updModeForRule{LHS,RHS}` in GHC.Core.Opt.Simplify.Utils) but they are still part of `SimplMode` as the caller of the Simplify pass needs to provide the initial values for those fields. @@ -250,7 +251,7 @@ seOptCoercionOpts :: SimplEnv -> OptCoercionOpts seOptCoercionOpts env = sm_co_opt_opts (seMode env) -sePhase :: SimplEnv -> CompilerPhase+sePhase :: SimplEnv -> SimplPhase sePhase env = sm_phase (seMode env)  sePlatform :: SimplEnv -> Platform@@ -270,7 +271,7 @@  -- See Note [The environments of the Simplify pass] data SimplMode = SimplMode -- See comments in GHC.Core.Opt.Simplify.Monad-  { sm_phase        :: !CompilerPhase+  { sm_phase        :: !SimplPhase    -- ^ The phase of the simplifier   , sm_names        :: ![String]      -- ^ Name(s) of the phase   , sm_rules        :: !Bool          -- ^ Whether RULES are enabled   , sm_inline       :: !Bool          -- ^ Whether inlining is enabled@@ -288,13 +289,85 @@   , sm_co_opt_opts :: !OptCoercionOpts -- ^ Coercion optimiser options   } +-- | See Note [SimplPhase]+data SimplPhase+  -- | A simplifier phase: InitialPhase, Phase 2, Phase 1, Phase 0, FinalPhase+  -- NB: (SimplPhase p) is equivalent to (SimplPhaseRange p p)+  = SimplPhase CompilerPhase++  -- | Simplifying the RHS of a rule or of a stable unfolding: the range of+  -- phases of the activation of the rule/stable unfolding.+  --+  -- _Invariant:_ 'simplStartPhase' is not a later phase than 'simplEndPhase'.+  -- Equivalently, 'SimplPhaseRange' is always a non-empty interval of phases.+  --+  -- See Note [What is active in the RHS of a RULE or unfolding?]+  --     in GHC.Core.Opt.Simplify.Utils.+  | SimplPhaseRange CompilerPhase CompilerPhase++  deriving Eq++simplStartPhase :: SimplPhase -> CompilerPhase+simplStartPhase (SimplPhase p)        = p+simplStartPhase (SimplPhaseRange p _) = p++simplEndPhase :: SimplPhase -> CompilerPhase+simplEndPhase (SimplPhase p)        = p+simplEndPhase (SimplPhaseRange _ p) = p++instance Outputable SimplPhase where+  ppr (SimplPhase p) = ppr p+  ppr (SimplPhaseRange s e) = brackets $ ppr s <> text "..." <> ppr e++-- | Is this activation active in this simplifier phase?+--+-- For a phase range, @isActive simpl_phase_range act@ is true if and only if+-- @act@ is active throughout the entire range, as per+-- Note [What is active in the RHS of a RULE or unfolding?] in GHC.Core.Opt.Simplify.Utils.+--+-- See Note [SimplPhase].+isActive :: SimplPhase -> Activation -> Bool+isActive (SimplPhase p) act+  = isActiveInPhase p act+isActive (SimplPhaseRange start end) act+  = -- To check whether the activation is active throughout the whole phase range,+    -- it's sufficient to check the endpoints of the phase range, because an+    -- activation can never have gaps (all activations are phase intervals).+    isActiveInPhase start act && isActiveInPhase end act++{- Note [SimplPhase]+~~~~~~~~~~~~~~~~~~~~+In general, the simplifier is invoked in successive phases:++  InitialPhase, Phase 2, Phase 1, Phase 0, FinalPhase++This allows us to control which rules, specialisations and inlinings are+active at any given point. For example,++  {-# RULE "myRule" [1] lhs = rhs #-}++starts being active in Phase 1, and stays active thereafter. Thus it is active+in Phase 1, Phase 0, FinalPhase, but not active in InitialPhase or Phase 2.++This simplifier phase is stored in the sm_phase field of SimplMode, usin+the 'SimplPhase' constructor. This allows us to determine which rules/inlinings+are active.++When we invoke the simplifier on the RHS of a rule, such as 'rhs' above, instead+of setting the simplifier mode to a single phase, we use a phase range+corresponding to the range of phases in which the rule is active, with the+'SimplPhaseRange' constructor. This allows us to check whether other rules or+inlinings are active throughout the whole activation of the rule.+See Note [What is active in the RHS of a RULE or unfolding?] in GHC.Core.Opt.Simplify.Utils.+-}+ instance Outputable SimplMode where-    ppr (SimplMode { sm_phase = p , sm_names = ss+    ppr (SimplMode { sm_phase = phase , sm_names = ss                    , sm_rules = r, sm_inline = i                    , sm_cast_swizzle = cs                    , sm_eta_expand = eta, sm_case_case = cc })        = text "SimplMode" <+> braces (-         sep [ text "Phase =" <+> ppr p <+>+         sep [ text "Phase =" <+> ppr phase <+>                brackets (text (concat $ intersperse "," ss)) <> comma              , pp_flag i   (text "inline") <> comma              , pp_flag r   (text "rules") <> comma@@ -312,9 +385,8 @@   | FloatNestedOnly    -- Local let-floating for nested (NotTopLevel) bindings only   | FloatEnabled       -- Do local let-floating on all bindings -{--Note [Local floating]-~~~~~~~~~~~~~~~~~~~~~+{- Note [Local floating]+~~~~~~~~~~~~~~~~~~~~~~~~ The Simplifier can perform local let-floating: it floats let-bindings out of the RHS of let-bindings.  See   Let-floating: moving bindings to give faster programs (ICFP'96)
GHC/Core/Opt/Simplify/Inline.hs view
@@ -29,7 +29,7 @@ import GHC.Types.Id import GHC.Types.Var.Env( InScopeSet, lookupInScope ) import GHC.Types.Var.Set-import GHC.Types.Basic  ( Arity, RecFlag(..), isActive )+import GHC.Types.Basic  ( Arity, RecFlag(..) ) import GHC.Utils.Logger import GHC.Utils.Misc import GHC.Utils.Outputable@@ -124,7 +124,7 @@   | isCompulsoryUnfolding (realIdUnfolding id)   = True   -- Even sm_inline can't override compulsory unfoldings   | otherwise-  = isActive (sm_phase mode) (idInlineActivation id)+  =  isActive (sm_phase mode) (idInlineActivation id)   && sm_inline mode       -- `or` isStableUnfolding (realIdUnfolding id)       -- Inline things when
GHC/Core/Opt/Simplify/Iteration.hs view
@@ -22,8 +22,8 @@ import GHC.Core.Opt.Simplify.Env import GHC.Core.Opt.Simplify.Inline import GHC.Core.Opt.Simplify.Utils-import GHC.Core.Opt.OccurAnal ( occurAnalyseExpr, zapLambdaBndrs, scrutOkForBinderSwap, BinderSwapDecision (..) )-import GHC.Core.Make       ( FloatBind, mkImpossibleExpr, castBottomExpr )+import GHC.Core.Opt.OccurAnal ( occurAnalyseExpr, zapLambdaBndrs )+import GHC.Core.Make       ( FloatBind, mkImpossibleExpr ) import qualified GHC.Core.Make import GHC.Core.Coercion hiding ( substCo, substCoVar ) import GHC.Core.Reduction@@ -471,14 +471,14 @@  Wrinkles -1. We must /not/ do cast w/w on+(CWW1) We must /not/ do cast w/w on      f = g |> co    otherwise it'll just keep repeating forever! You might think this    is avoided because the call to tryCastWorkerWrapper is guarded by-   preInlineUnconditinally, but I'm worried that a loop-breaker or an-   exported Id might say False to preInlineUnonditionally.+   preInlineUnconditionally, but I'm worried that a loop-breaker or an+   exported Id might say False to preInlineUnconditionally. -2. We need to be careful with inline/noinline pragmas:+(CWW2) We need to be careful with inline/noinline pragmas:        rec { {-# NOINLINE f #-}              f = (...g...) |> co            ; g = ...f... }@@ -493,15 +493,15 @@            f = $wf |> co          ; g = ...f... }    and that is bad: the whole point is that we want to inline that-   cast!  We want to transfer the pagma to $wf:+   cast!  We want to transfer the pragma to $wf:       rec { {-# NOINLINE $wf #-}             $wf = ...g...           ; f = $wf |> co           ; g = ...f... }    c.f. Note [Worker/wrapper for NOINLINE functions] in GHC.Core.Opt.WorkWrap. -3. We should still do cast w/w even if `f` is INLINEABLE.  E.g.-      {- f: Stable unfolding = <stable-big> -}+(CWW3) We should still do cast w/w even if `f` is INLINEABLE.  E.g.+      {- f: Stable unfolding (arity 2) = <stable-big> -}       f = (\xy. <big-body>) |> co    Then we want to w/w to       {- $wf: Stable unfolding = <stable-big> |> sym co -}@@ -510,16 +510,44 @@    Notice that the stable unfolding moves to the worker!  Now demand analysis    will work fine on $wf, whereas it has trouble with the original f.    c.f. Note [Worker/wrapper for INLINABLE functions] in GHC.Core.Opt.WorkWrap.-   This point also applies to strong loopbreakers with INLINE pragmas, see-   wrinkle (4). -4. We should /not/ do cast w/w for non-loop-breaker INLINE functions (hence-   hasInlineUnfolding in tryCastWorkerWrapper, which responds False to-   loop-breakers) because they'll definitely be inlined anyway, cast and-   all. And if we do cast w/w for an INLINE function with arity zero, we get+(CWW4) We should /not/ do cast w/w for INLINE functions (hence `hasInlineUnfolding`+   in `tryCastWorkerWrapper`) because they'll definitely be inlined anyway, cast+   and all.++   Moreover, if we do cast w/w for an INLINE function with arity zero, we get    something really silly: we inline that "worker" right back into the wrapper!-   Worse than a no-op, because we have then lost the stable unfolding.+   In fact it is Much Worse than a no-op, because we have then lost the stable+   unfolding --- aargh (see #26903).  E.g. similar example to (CWW3)+      {- g: Stable unfolding (arity 0) = <stable-big> -}   NB arity 0!+      g = (\xy. <big-body>) |> co+   If we w/w to this:+      {- $wg: Stable unfolding (arity 0) = <stable-big> |> sym co -}+      $wg = \xy. <big-body>+      g = $wg |> co+   then we'll inline $wg at the call site in `g` giving+      {- $wg: Stable unfolding (arity 0) = <stable-big> |> sym co -}+      $wg = \xy. <big-body>+      g = (<stable-big> |> sym co) |> co+   and now we'll drop `$wg` as dead and we have lost the unfolding on `g`.+   (We could /also/ give the binding `g = $wf |> co` a stable unfolding. Then+   things would work right; but there is also no point in doing the cast+   worker/wrapper in the first place.) +   NB: you might wonder about a loop-breaker with an INLINE pragma; after all, a+   loop breaker won't "definitely be inlined anyway", so arguably we should not+   disable cast w/w/ for it.  But a Rec group can /look/ recursive at an early+   stage, and subsequently /become/ non-recursive after some simplification.+   (This is common in instance decls; see Note [Checking for INLINE loop breakers]+   in GHC.Core.Lint.)  So the danger is that we'll permanently lose that stable+   unfolding that we specifically wanted (#26903).  Simple solution: disable cast+   w/w for /any/ INLINE function.  See the defn+   of `GHC.Types.Id.Info.hasInlineUnfolding`.++   The danger is that an INLINE pragma on a genuninely-recursive function+   will kill worker-wrapper.  Well, so be it.  They are pretty suspicious anyway;+   see Note [Checking for INLINE loop breakers].+ All these wrinkles are exactly like worker/wrapper for strictness analysis:   f is the wrapper and must inline like crazy   $wf is the worker and must carry f's original pragma@@ -583,11 +611,11 @@   | BC_Let top_lvl is_rec <- bind_cxt  -- Not join points   , not (isDFunId bndr) -- nor DFuns; cast w/w is no help, and we can't transform                         --            a DFunUnfolding in mk_worker_unfolding-  , not (exprIsTrivial rhs)        -- Not x = y |> co; Wrinkle 1-  , not (hasInlineUnfolding info)  -- Not INLINE things: Wrinkle 4-  , typeHasFixedRuntimeRep work_ty    -- Don't peel off a cast if doing so would-                                      -- lose the underlying runtime representation.-                                      -- See Note [Preserve RuntimeRep info in cast w/w]+  , not (exprIsTrivial rhs)          -- Not x = y |> co; see (CWW1)+  , not (hasInlineUnfolding info)    -- Not INLINE things: see (CWW4)+  , typeHasFixedRuntimeRep work_ty   -- Don't peel off a cast if doing so would+                                     -- lose the underlying runtime representation.+                                     -- See Note [Preserve RuntimeRep info in cast w/w]   , not (isOpaquePragma (idInlinePragma old_bndr)) -- Not for OPAQUE bindings                                                    -- See Note [OPAQUE pragma]   = do  { uniq <- getUniqueM@@ -634,13 +662,13 @@                               `setArityInfo`      work_arity            -- We do /not/ want to transfer OccInfo, Rules            -- Note [Preserve strictness in cast w/w]-           -- and Wrinkle 2 of Note [Cast worker/wrapper]+           -- and (CWW2) of Note [Cast worker/wrapper]      ----------- Worker unfolding -----------     -- Stable case: if there is a stable unfolding we have to compose with (Sym co);     --   the next round of simplification will do the job     -- Non-stable case: use work_rhs-    -- Wrinkle 3 of Note [Cast worker/wrapper]+    -- See (CWW4) of Note [Cast worker/wrapper]     mk_worker_unfolding top_lvl work_id work_rhs       = case realUnfoldingInfo info of -- NB: the real one, even for loop-breakers            unf@(CoreUnfolding { uf_tmpl = unf_rhs, uf_src = src })@@ -1705,6 +1733,7 @@                                    , sc_hole_ty = coercionLKind co }) }                                         -- NB!  As the cast goes past, the                                         -- type of the hole changes (#16312)+         -- (f |> co) e   ===>   (f (e |> co1)) |> co2         -- where   co :: (s1->s2) ~ (t1->t2)         --         co1 :: t1 ~ s1@@ -1839,7 +1868,7 @@             , not ( isSimplified dup &&  -- See (SR2) in Note [Avoiding simplifying repeatedly]                     not (exprIsTrivial arg) &&                     not (isDeadOcc (idOccInfo bndr)) )-            -> do { simplTrace "SimplBindr:inline-uncond3" (ppr bndr) $+            -> do { simplTrace "SimplBindr:inline-uncond3" (ppr bndr <+> text ":=" <+> ppr arg $$ ppr (seIdSubst env)) $                     tick (PreInlineUnconditionally bndr)                   ; simplLam env' body cont } @@ -2370,24 +2399,9 @@  ---------- Bottoming applications -------------- rebuildCall env (ArgInfo { ai_fun = fun, ai_args = rev_args, ai_dmds = [] }) cont-  -- When we run out of strictness args, it means-  -- that the call is definitely bottom; see GHC.Core.Opt.Simplify.Utils.mkArgInfo-  -- Then we want to discard the entire strict continuation.  E.g.-  --    * case (error "hello") of { ... }-  --    * (error "Hello") arg-  --    * f (error "Hello") where f is strict-  --    etc-  -- Then, especially in the first of these cases, we'd like to discard-  -- the continuation, leaving just the bottoming expression.  But the-  -- type might not be right, so we may have to add a coerce.-  | not (contIsTrivial cont)     -- Only do this if there is a non-trivial-                                 -- continuation to discard, else we do it-                                 -- again and again!-  = seqType cont_ty `seq`        -- See Note [Avoiding space leaks in OutType]-    return (emptyFloats env, castBottomExpr res cont_ty)-  where-    res     = argInfoExpr fun rev_args-    cont_ty = contResultType cont+  -- When we run out of demands, it means that the call is definitely bottom.+  -- See (TC2) in Note [Trimming the continuation for bottoming functions]+  = rebuild env (argInfoExpr fun rev_args) (mkBottomCont env cont)  ---------- Simplify type applications -------------- rebuildCall env info (ApplyToTy { sc_arg_ty = arg_ty, sc_hole_ty = hole_ty, sc_cont = cont })@@ -2458,7 +2472,11 @@       | not (logHasDumpFlag logger Opt_D_verbose_core2core)       = when (isExternalName (idName var)) $             log_inlining $-                sep [text "Inlining done:", nest 4 (ppr var)]+              sep [text "Inlining done:", nest 4 (ppr var)]+            --  $$ nest 2 (vcat+            --       [ text "Simplifier phase:" <+> ppr (sePhase env)+            --       , text "Unfolding activation:" <+> ppr (idInlineActivation var)+            --       ])       | otherwise       = log_inlining $            sep [text "Inlining done: " <> ppr var,@@ -2645,6 +2663,8 @@       = log_rule Opt_D_dump_rule_rewrites "Rule fired" $ vcat           [ text "Rule:" <+> ftext (ruleName rule)           , text "Module:" <+>  printRuleModule rule+        --, text "Simplifier phase:" <+> ppr (sePhase env)+        --, text "Rule activation:" <+> ppr (ruleActivation rule)           , text "Full arity:" <+>  ppr (ruleArity rule)           , text "Before:" <+> hang (ppr fn) 2 (sep (map ppr args))           , text "After: " <+> pprCoreExpr rule_rhs ]@@ -3596,11 +3616,13 @@     env1 = addBinderUnfolding env case_bndr con_app_unf      -- See Note [Add unfolding for scrutinee]+    -- e.g. case (x |> co) of K a b -> blah+    --      We add to `x` the unfolding  (K a b |> sym co)     env2 | DoBinderSwap v mco <- bndr_swap          = addBinderUnfolding env1 v $               if isReflMCo mco  -- isReflMCo: avoid calling mk_simple_unf               then con_app_unf  --            twice in the common case-              else mk_simple_unf (mkCastMCo con_app mco)+              else mk_simple_unf (mkCastMCo con_app (mkSymMCo mco))           | otherwise = env1 @@ -3821,6 +3843,41 @@ then we can just duplicate those alts because the A and C cases will disappear immediately.  This is more direct than creating join points and inlining them away.  See #4930.++Note [Trimming the continuation for bottoming functions]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+Suppose+   f :: Int -> Int -> Int+   f x = error "urk"++   foo = f 3 4++f's demand signature say "after one arg I return bottom".  We can drop+the remaining arguments, thus++   foo = case f 3 of {}++This trimming can also be done with other continuations:+   * case (error "hello") of { ... }+   * f (error "Hello") where f is strict+   etc++We implement the trimming in three parts:++(TC1) In `mkArgInfo`, for a bottoming function, we make a list of `RemainingArgDmds`+  with a finite list of elements (in the example above, just one).++  For comparison, note that, for non-bottoming functions, the `RemainingArgDmds`+  always finishes with an infinite list of `topDmd`.++(TC2) In `rebuildCall`, when we run out of `RemainingArgDmds` we discard the+  remaining continuation.++  After discarding the continuation, the types might not match, in which case+  we leave behind a (case <hole> of {}) wrapper.  See the call to `mkBottomCont`.++(TC3) In `mkDupableContWithDmds`, we similarly discard the continuation when+  we run out of `RemainingArgDmds`. -}  --------------------@@ -3868,6 +3925,13 @@  mkDupableContWithDmds _ _ (Stop {}) = panic "mkDupableCont"     -- Handled by previous eqn +mkDupableContWithDmds env dmds cont+  -- No more demands => function is definitely bottom+  --                 => simply trim the continuation+  -- c.f. the null-demands case in `rebuildCall`+  -- See (TC3) in Note [Trimming the continuation for bottoming functions]+  | [] <- dmds = return (emptyFloats env, mkBottomCont env cont)+ mkDupableContWithDmds env dmds (CastIt { sc_co = co, sc_opt = opt, sc_cont = cont })   = do  { (floats, cont') <- mkDupableContWithDmds env dmds cont         ; return (floats, CastIt { sc_co = optOutCoercion env co opt@@ -3943,7 +4007,7 @@         ; return (floats, ApplyToTy { sc_cont = cont'                                     , sc_arg_ty = arg_ty, sc_hole_ty = hole_ty }) } -mkDupableContWithDmds env dmds+mkDupableContWithDmds env (dmd : cont_dmds)     (ApplyToVal { sc_arg = arg, sc_dup = dup, sc_env = se                 , sc_cont = cont, sc_hole_ty = hole_ty })   =     -- e.g.         [...hole...] (...arg...)@@ -3951,8 +4015,7 @@         --              let a = ...arg...         --              in [...hole...] a         -- NB: sc_dup /= OkToDup; that is caught earlier by contIsDupable-    do  { let dmd:|cont_dmds = expectNonEmpty dmds-        ; (floats1, cont') <- mkDupableContWithDmds env cont_dmds cont+    do  { (floats1, cont') <- mkDupableContWithDmds env cont_dmds cont         ; let env' = env `setInScopeFromF` floats1         ; (_, se', arg') <- simplLazyArg env' dup hole_ty Nothing se arg         ; (let_floats2, arg'') <- makeTrivial env NotTopLevel dmd (fsLit "karg") arg'@@ -3966,7 +4029,6 @@                                          -- See Note [StaticEnv invariant] in GHC.Core.Opt.Simplify.Utils                               , sc_dup = OkToDup, sc_cont = cont'                               , sc_hole_ty = hole_ty }) }- mkDupableContWithDmds env _     (Select { sc_bndr = case_bndr, sc_alts = alts, sc_env = se, sc_cont = cont })   =     -- e.g.         (case [...hole...] of { pi -> ei })@@ -4790,9 +4852,12 @@                  rhs_cont = case bind_cxt of  -- See Note [Rules and unfolding for join points]                                 BC_Let {}      -> mkBoringStop rhs_ty                                 BC_Join _ cont -> assertPpr join_ok bad_join_msg cont-                 lhs_env = updMode updModeForRules env'-                 rhs_env = updMode (updModeForStableUnfoldings act) env'-                           -- See Note [Simplifying the RHS of a RULE]++    -- See Note [Simplifying rules] and Note [What is active in the RHS of a RULE or unfolding?]+    -- in GHC.Core.Opt.Simplify.Utils.+                 lhs_env = updMode updModeForRuleLHS env'+                 rhs_env = updMode (updModeForRuleRHS act) env'+                  -- Force this to avoid retaining reference to old Id                  !fn_name' = case mb_new_id of                               Just id -> idName id@@ -4816,12 +4881,3 @@                           , ru_rhs   = occurAnalyseExpr rhs' }) }                             -- Remember to occ-analyse, to drop dead code.                             -- See Note [OccInfo in unfoldings and rules] in GHC.Core--{- Note [Simplifying the RHS of a RULE]-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-We can simplify the RHS of a RULE much as we do the RHS of a stable-unfolding.  We used to use the much more conservative updModeForRules-for the RHS as well as the LHS, but that seems more conservative-than necesary.  Allowing some inlining might, for example, eliminate-a binding.--}
GHC/Core/Opt/Simplify/Utils.hs view
@@ -15,7 +15,7 @@         preInlineUnconditionally, postInlineUnconditionally,         activeRule,         getUnfoldingInRuleMatch,-        updModeForStableUnfoldings, updModeForRules,+        updModeForStableUnfoldings, updModeForRuleLHS, updModeForRuleRHS,          -- The BindContext type         BindContext(..), bindContextLevel,@@ -24,7 +24,7 @@         SimplCont(..), DupFlag(..), FromWhat(..), StaticEnv,         isSimplified, contIsStop,         contIsDupable, contResultType, contHoleType, contHoleScaling,-        contIsTrivial, contArgs, contIsRhs,+        contIsTrivial, contArgs, contIsRhs, mkBottomCont,         countArgs, contOutArgs, dropContArgs,         mkBoringStop, mkRhsStop, mkLazyArgStop,         interestingCallContext,@@ -72,6 +72,7 @@ import GHC.Types.Demand import GHC.Types.Var.Set import GHC.Types.Basic+import GHC.Types.Name.Env  import GHC.Data.OrdList ( isNilOL ) import GHC.Data.FastString ( fsLit )@@ -81,10 +82,12 @@ import GHC.Utils.Outputable import GHC.Utils.Panic -import Control.Monad    ( when )+import Control.Monad    ( guard, when ) import Data.List        ( sortBy )-import GHC.Types.Name.Env+import Data.Maybe import Data.Graph+import GHC.Core.TyCo.Compare (eqTypeIgnoringMultiplicity)+import GHC.Core.Make (mkWildValBinder)  {- ********************************************************************* *                                                                      *@@ -461,6 +464,20 @@ contIsTrivial _                                                 = False  -------------------+contStop :: SimplCont -> SimplCont+-- ^ Get the 'Stop' at the tail of the continuation+--+-- Always returns a continuation of form @(Stop ...)@.+contStop stop@(Stop {})               = stop+contStop (CastIt { sc_cont = k })     = contStop k+contStop (StrictBind { sc_cont = k }) = contStop k+contStop (StrictArg { sc_cont = k })  = contStop k+contStop (Select { sc_cont = k })     = contStop k+contStop (ApplyToTy  { sc_cont = k }) = contStop k+contStop (ApplyToVal { sc_cont = k }) = contStop k+contStop (TickIt _ k)                 = contStop k++------------------- contResultType :: SimplCont -> OutType contResultType (Stop ty _ _)                = ty contResultType (CastIt { sc_cont = k })     = contResultType k@@ -607,6 +624,39 @@     -- and case binder dmds, see addCaseBndrDmd. No priority right now.  -------------------+mkBottomCont :: StaticEnv -> SimplCont -> SimplCont+-- ^ Given a continuation `cont`, return a `cont` /of the same type/,+-- looking like @(case \<hole\> of {})@.+--+-- This is used when we are going to fill in the @<hole>@ with bottom.+-- See (TC2,3) in Note [Trimming the continuation for bottoming functions]+--+-- Don't bother to trim, making a @case <hole> of {}@, if we have only+-- an essentially-trivial continuation; e.g. @(<hole> \@ty |> co)@.+mkBottomCont se cont = go cont+  where+    go k@(Stop {})                    = k+    go (TickIt t k')                  = TickIt t (go k')+    go k@(CastIt    { sc_cont = k' }) = k { sc_cont = go k' }+    go k@(ApplyToTy { sc_cont = k' }) = k { sc_cont = go k' }+    go k@(Select { sc_alts = [], sc_cont = Stop {} }) = k  -- Optimisation only+    go k | Stop res_ty _ _ <- stop_cont+         = if  hole_ty `eqTypeIgnoringMultiplicity` res_ty+              then stop_cont+              else Select { sc_alts = []+                          , sc_bndr = mkWildValBinder OneTy hole_ty+                          , sc_dup  = OkToDup+                          , sc_env  = zapSubstEnv se+                          -- `hole_ty` is an `OutType`, but `sc_bndr` is an `InId`;+                          -- so we must zap the substitution in `sc_env`.+                          , sc_cont = stop_cont }+         | otherwise = panic "stop_cont is not Stop {}"+         where+           hole_ty   = contHoleType k+           stop_cont = contStop k+++------------------- mkArgInfo :: SimplEnv -> Id -> [CoreRule] -> SimplCont -> ArgInfo mkArgInfo env fun rules_for_fun cont   | n_val_args < idArity fun            -- Note [Unsaturated functions]@@ -719,7 +769,7 @@  This is a pretty pathological example, so I'm not losing sleep over it, but the simplest solution was to check sm_inline; if it is False,-which it is on the LHS of a rule (see updModeForRules), then don't+which it is on the LHS of a rule (see updModeForRuleLHS), then don't make use of the strictness info for the function. -} @@ -1069,22 +1119,22 @@  updModeForStableUnfoldings :: Activation -> SimplMode -> SimplMode -- See Note [The environments of the Simplify pass]+-- See Note [Simplifying inside stable unfoldings] updModeForStableUnfoldings unf_act current_mode-  = current_mode { sm_phase      = phaseFromActivation unf_act-                 , sm_eta_expand = False-                 , sm_inline     = True }-       -- sm_eta_expand: see Note [Eta expansion in stable unfoldings and rules]-       -- sm_rules: just inherit; sm_rules might be "off"-       --           because of -fno-enable-rewrite-rules-  where-    phaseFromActivation (ActiveAfter _ n) = Phase n-    phaseFromActivation _                 = InitialPhase+  = current_mode+    { sm_phase = phaseForRuleOrUnf (sm_phase current_mode) unf_act+        -- See Note [What is active in the RHS of a RULE or unfolding?]+    , sm_eta_expand = False+        -- See Note [Eta expansion in stable unfoldings and rules]+    , sm_inline     = True+   -- sm_rules: just inherit; sm_rules might be "off" because of -fno-enable-rewrite-rules+    } -updModeForRules :: SimplMode -> SimplMode+updModeForRuleLHS :: SimplMode -> SimplMode -- See Note [Simplifying rules] -- See Note [The environments of the Simplify pass]-updModeForRules current_mode-  = current_mode { sm_phase        = InitialPhase+updModeForRuleLHS current_mode+  = current_mode { sm_phase        = SimplPhase InitialPhase -- doesn't matter                  , sm_inline       = False                       -- See Note [Do not expose strictness if sm_inline=False]                  , sm_rules        = False@@ -1092,8 +1142,39 @@                       -- See Note [Cast swizzling on rule LHSs]                  , sm_eta_expand   = False } +updModeForRuleRHS :: Activation -> SimplMode -> SimplMode+updModeForRuleRHS rule_act current_mode =+  current_mode+    -- See Note [What is active in the RHS of a RULE or unfolding?]+    { sm_phase = phaseForRuleOrUnf (sm_phase current_mode) rule_act+    , sm_eta_expand = False+        -- See Note [Eta expansion in stable unfoldings and rules]+    }++-- | `phaseForRuleOrUnf` computes the phase range to use when+-- simplifying the RHS of a rule or of a stable unfolding.+--+-- This subtle function implements the careful plan described in+-- See Note [What is active in the RHS of a RULE or unfolding?]+phaseForRuleOrUnf+  :: SimplPhase    -- ^ the current simplifier phase+  -> Activation    -- ^ the activation of the RULE or stable unfolding+  -> SimplPhase+phaseForRuleOrUnf current_phase act+  | start == end+  = SimplPhase start+  | otherwise+  = SimplPhaseRange start end+  where+    start, end :: CompilerPhase+    start = beginPhase act `earliestPhase` simplStartPhase current_phase+    end   = endPhase   act `latestPhase`   simplEndPhase   current_phase+    -- The beginPhase/endPhase           implements (WAR1)+    -- The simplStartPhase/simplEndPhase implements (WAR2)+    -- of Note [What is active in the RHS of a RULE or unfolding?]+ {- Note [Simplifying rules]-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+~~~~~~~~~~~~~~~~~~~~~~~~~~~ When simplifying a rule LHS, refrain from /any/ inlining or applying of other RULES. Doing anything to the LHS is plain confusing, because it means that what the rule matches is not what the user@@ -1136,7 +1217,7 @@ coercion /variables/, not general coercions, on the LHS of a RULE.  So we don't want to swizzle this to       (\x. blah) |> (Refl xty `FunCo` CoVar cv)-So we switch off cast swizzling in updModeForRules.+So we switch off cast swizzling in updModeForRuleLHS.  Note [Eta expansion in stable unfoldings and rules] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~@@ -1200,6 +1281,84 @@ anything, because the byte-code interpreter might get confused about unboxed tuples and suchlike. +Note [What is active in the RHS of a RULE or unfolding?]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+Suppose we have either a RULE or an inline pragma with an explicit activation:++  {-# RULE "R" [p] lhs = rhs #-}+  {-# INLINE [p] foo #-}++We should do some modest rules/inlining stuff in the right-hand sides, partly to+eliminate senseless crap, and partly to break the recursive knots generated by+instance declarations. However, we have to be careful about precisely which+rules/inlinings are active. In particular:++  a) Rules/inlinings that *cease* being active before p should not apply.+  b) Rules/inlinings that only become active *after* p should also not apply.++In the rest of this Note, we will focus on rules, but everything applies equally+to the RHSs of stable unfoldings.++Our carefully crafted plan is as follows:++  -------------------------------------------------------------+  When simplifying the RHS of a RULE R with activation range A,+  fire only other rules R' that are active+      (WAR1) throughout all of A+      (WAR2) in the current phase+  See `phaseForRuleOrUnf`.+  -------------------------------------------------------------++Reasons for (WAR1):+  * R might fire in any phase in A. Then R' can fire only if R' is active in that+    phase. If not, it's not safe to unconditionally fire R' in the RHS of R.++Reasons for (WAR2):+  * If A is empty (e.g. a NOINLINE pragma, so the unfolding is never active)+    we don't want to vacuously satisfy (WAR1) and thereby fire /all/ RULES in+    the unfolding.  Two RULES may be crafted so that they are never simultaneously+    active, and will loop if they are.++  * Suppose we are in Phase 2, looking at a stable unfolding for INLINE [1].+    If we just do (WAR1) we will fire RULES active in phase 1; but the+    occurrence analyser ignores any rules not active in the current phase.+    So occ-anal may fail to detect a loop breaker; see #26826 for details.+    See Note [Rules and loop breakers] in GHC.Core.Opt.OccurAnal.++  * Aesthetically, this means that when the simplifer is in phase N, it+    won't switch to a phase-range that doesn't include N (e.g. might be later+    than N).  This is what caused #26826.++  * Also note that as the current phase advances, it'll eventually be inside+    the range specified by (WAR1), and hence will not widen the range.+    Unless the latter is empty, of course.++This plan is implemented by:++  1. Setting the simplifier phase to the /range/ of phases+     corresponding to the start/end phases of the rule's activation, implementing+     (WAR1) and (WAR2). This happens in `phaseForRuleOrUnf`.++  2. When checking whether another rule is active, we use the function+       isActive :: SimplPhase -> Activation -> Bool+     from GHC.Core.Opt.Simplify.Env, which checks whether the other rule is+     active throughout the whole range of phases.++You might wonder about a situation such as the following:++  module M1 where+    {-# RULES "r1" [1] lhs1 = rhs1 #-}+    {-# RULES "r2" [2] lhs2 = rhs2 #-}++    Current simplifier phase: 1++It looks tempting to use "r1" when simplifying the RHS of "r2", yet we+**must not** do so: for any module M that imports M1, we are going to start+simplification in M starting at InitialPhase, and we will see the+fully simplified rules RHSs imported from M1.++Conclusion: stick to the plan.+ Note [Simplifying inside stable unfoldings] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We must take care with simplification inside stable unfoldings (which come from@@ -1216,33 +1375,9 @@ any occurrence in a stable unfolding as a multiple occurrence, not a single one; see OccurAnal.addRuleUsage. -Second, we do want *do* to some modest rules/inlining stuff in stable-unfoldings, partly to eliminate senseless crap, and partly to break-the recursive knots generated by instance declarations.--However, suppose we have-        {-# INLINE <act> f #-}-        f = <rhs>-meaning "inline f in phases p where activation <act>(p) holds".-Then what inlinings/rules can we apply to the copy of <rhs> captured in-f's stable unfolding?  Our model is that literally <rhs> is substituted for-f when it is inlined.  So our conservative plan (implemented by-updModeForStableUnfoldings) is this:--  --------------------------------------------------------------  When simplifying the RHS of a stable unfolding, set the phase-  to the phase in which the stable unfolding first becomes active-  ---------------------------------------------------------------That ensures that--  a) Rules/inlinings that *cease* being active before p will-     not apply to the stable unfolding, consistent with it being-     inlined in its *original* form in phase p.--  b) Rules/inlinings that only become active *after* p will-     not apply to the stable unfolding, again to be consistent with-     inlining the *original* rhs in phase p.+Second, we must be careful when simplifying the RHS that we do not apply RULES+which are not active over the whole active range of the stable unfolding.+This is all explained in Note [What is active in the RHS of a RULE or unfolding?].  For example,         {-# INLINE f #-}@@ -1291,8 +1426,7 @@   = ISE in_scope id_unf   where     in_scope = seInScope env-    phase    = sePhase env-    id_unf   = whenActiveUnfoldingFun (isActive phase)+    id_unf   = whenActiveUnfoldingFun (isActive (sePhase env))      -- When sm_rules was off we used to test for a /stable/ unfolding,      -- but that seems wrong (#20941) @@ -1468,7 +1602,8 @@     one_occ _                                     = False      pre_inline_unconditionally = sePreInline env-    active = isActive (sePhase env) (inlinePragmaActivation inline_prag)+    active = isActive (sePhase env)+           $ inlinePragmaActivation inline_prag              -- See Note [pre/postInlineUnconditionally in gentle mode]     inline_prag = idInlinePragma bndr @@ -1504,7 +1639,10 @@       -- not ticks.  Counting ticks cannot be duplicated, and non-counting       -- ticks around a Lam will disappear anyway. -    early_phase = sePhase env /= FinalPhase+    early_phase =+      case sePhase env of+        SimplPhase p -> p /= FinalPhase+        SimplPhaseRange _start end -> end /= FinalPhase     -- If we don't have this early_phase test, consider     --      x = length [1,2,3]     -- The full laziness pass carefully floats all the cons cells to@@ -1515,9 +1653,8 @@     --     -- On the other hand, I have seen cases where top-level fusion is     -- lost if we don't inline top level thing (e.g. string constants)-    -- Hence the test for phase zero (which is the phase for all the final-    -- simplifications).  Until phase zero we take no special notice of-    -- top level things, but then we become more leery about inlining+    -- Hence the final phase test: until the final phase, we take no special+    -- notice of top level things, but then we become more leery about inlining     -- them.     --     -- What exactly to check in `early_phase` above is the subject of #17910.@@ -1644,8 +1781,7 @@     occ_info    = idOccInfo old_bndr     unfolding   = idUnfolding bndr     uf_opts     = seUnfoldingOpts env-    phase       = sePhase env-    active      = isActive phase (idInlineActivation bndr)+    active      = isActive (sePhase env) $ idInlineActivation bndr         -- See Note [pre/postInlineUnconditionally in gentle mode]  {- Note [Inline small things to avoid creating a thunk]@@ -2456,8 +2592,28 @@                 True  -> True;                 False -> False -and similar friends.+and similar friends.  There are some tricky wrinkles: +(EIC1) Casts. We've seen this:+            case e of x { _ -> x `cast` c }+       And we definitely want to eliminate this case, to give+            e `cast` c+(EIC2) Ticks. Similarly+            case e of x { _ -> Tick t x }+       At least if the tick is 'floatable' we want to eliminate the case+       to give+            Tick t e++So `check_eq` strips off enclosing casts and ticks from the RHS of the+alternative, returning a wrapper function that will rebuild them around+the scrutinee if case-elim is successful.++(EIC3) What if there are many alternatives, all identities. If casts+  are involved they must be the same cast, to make the types line up.+  In principle there could be different ticks in each RHS, but we just+  pick the ticks from the first alternative.  (In the common case there+  is only one alternative.)+ Note [Scrutinee Constant Folding] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~      case x op# k# of _ {  ===> case x of _ {@@ -2633,7 +2789,7 @@  mkCase mode scrut outer_bndr alts_ty alts   | sm_case_merge mode-  , Just (joins, alts') <- mergeCaseAlts outer_bndr alts+  , Just (joins, alts') <- mergeCaseAlts scrut outer_bndr alts   = do  { tick (CaseMerge outer_bndr)         ; case_expr <- mkCase1 mode scrut outer_bndr alts_ty alts'         ; return (mkLets joins case_expr) }@@ -2650,44 +2806,46 @@ --         See Note [Eliminate Identity Case] -------------------------------------------------- -mkCase1 _mode scrut case_bndr _ alts@(Alt _ _ rhs1 : alts')      -- Identity case-  | all identity_alt alts+mkCase1 _mode scrut case_bndr _ (alt1 : alts)      -- Identity case+  | Just wrap <- identity_alt alt1   -- `wrap`: see (EIC1) and (EIC2)+  , all (isJust . identity_alt) alts -- See (EIC3) in Note [Eliminate Identity Case]   = do { tick (CaseIdentity case_bndr)-       ; return (mkTicks ticks $ re_cast scrut rhs1) }+       ; return (wrap scrut) }   where-    ticks = concatMap (\(Alt _ _ rhs) -> stripTicksT tickishFloatable rhs) alts'-    identity_alt (Alt con args rhs) = check_eq rhs con args+    identity_alt :: CoreAlt -> Maybe (CoreExpr -> CoreExpr)+    identity_alt (Alt con args rhs) = check_eq con args rhs -    check_eq (Cast rhs co) con args        -- See Note [RHS casts]-      = not (any (`elemVarSet` tyCoVarsOfCo co) args) && check_eq rhs con args-    check_eq (Tick t e) alt args-      = tickishFloatable t && check_eq e alt args+    check_eq :: AltCon -> [Var] -> CoreExpr -> Maybe (CoreExpr -> CoreExpr)+    -- (check_eq con args e) return True if+    --       e   looks like   (Tick (Cast (Tick (con args))))+    -- where (con args) is the LHS of the alternative+    -- In that case it returns (\e. Tick (Cast (Tick e))),+    -- a wrapper function that can rebuild the tick/cast stuff+    -- See (EIC1) and (EIC2) in Note [Eliminate Identity Case]+    check_eq alt_con args (Cast e co)         -- See (EIC1)+      = do { guard (not (any (`elemVarSet` tyCoVarsOfCo co) args))+           ; wrap <- check_eq alt_con args e+           ; return (flip mkCast co . wrap) }+    check_eq alt_con args (Tick t e)          -- See (EIC2)+      = do { guard (tickishFloatable t)+           ; wrap <- check_eq alt_con args e+           ; return (Tick t . wrap) }+    check_eq alt_con args e+      | is_id alt_con args e = Just (\e -> e)+      | otherwise            = Nothing -    check_eq (Lit lit) (LitAlt lit') _     = lit == lit'-    check_eq (Var v) _ _  | v == case_bndr = True-    check_eq (Var v)   (DataAlt con) args-      | null arg_tys, null args            = v == dataConWorkId con-                                             -- Optimisation only-    check_eq rhs        (DataAlt con) args = cheapEqExpr' tickishFloatable rhs $-                                             mkConApp2 con arg_tys args-    check_eq _          _             _    = False+    is_id :: AltCon -> [Var] -> CoreExpr -> Bool+    is_id _ _  (Var v) | v == case_bndr = True+    is_id (LitAlt lit') _ (Lit lit)     = lit == lit'+    is_id (DataAlt con) args rhs+      | Var v <- rhs   -- Optimisation only+      , null arg_tys+      , null args      = v == dataConWorkId con+      | otherwise      = cheapEqExpr' tickishFloatable rhs $+                         mkConApp2 con arg_tys args+    is_id _ _ _ = False      arg_tys = tyConAppArgs (idType case_bndr)--        -- Note [RHS casts]-        -- ~~~~~~~~~~~~~~~~-        -- We've seen this:-        --      case e of x { _ -> x `cast` c }-        -- And we definitely want to eliminate this case, to give-        --      e `cast` c-        -- So we throw away the cast from the RHS, and reconstruct-        -- it at the other end.  All the RHS casts must be the same-        -- if (all identity_alt alts) holds.-        ---        -- Don't worry about nested casts, because the simplifier combines them--    re_cast scrut (Cast rhs co) = Cast (re_cast scrut rhs) co-    re_cast scrut _             = scrut  mkCase1 mode scrut bndr alts_ty alts = mkCase2 mode scrut bndr alts_ty alts 
GHC/Core/Opt/SpecConstr.hs view
@@ -30,7 +30,6 @@ import GHC.Core.FVs     ( exprsFreeVarsList, exprFreeVars ) import GHC.Core.Opt.Monad import GHC.Core.Opt.WorkWrap.Utils-import GHC.Core.Opt.OccurAnal( BinderSwapDecision(..), scrutOkForBinderSwap ) import GHC.Core.DataCon import GHC.Core.Class( classTyVars ) import GHC.Core.Coercion hiding( substCo )
GHC/Core/Opt/Specialise.hs view
@@ -20,18 +20,22 @@ import GHC.Core.Predicate import GHC.Core.Class( classMethods ) import GHC.Core.Coercion( Coercion )-import GHC.Core.Opt.Monad+import GHC.Core.DataCon (dataConTyCon)+ import qualified GHC.Core.Subst as Core import GHC.Core.Unfold.Make import GHC.Core-import GHC.Core.Make      ( mkLitRubbish ) import GHC.Core.Unify     ( tcMatchTy ) import GHC.Core.Rules+import GHC.Core.Subst (substTickish)+import GHC.Core.TyCon (tyConClass_maybe) import GHC.Core.Utils     ( exprIsTrivial, exprIsTopLevelBindable                           , mkCast, exprType, exprIsHNF                           , stripTicksTop, mkInScopeSetBndrs ) import GHC.Core.FVs import GHC.Core.Opt.Arity( collectBindersPushingCo )+import GHC.Core.Opt.Monad+import GHC.Core.Opt.Simplify.Env ( SimplPhase(..), isActive )  import GHC.Builtin.Types  ( unboxedUnitTy ) @@ -66,9 +70,6 @@  import Data.List( partition ) import Data.List.NonEmpty ( NonEmpty (..) )-import GHC.Core.Subst (substTickish)-import GHC.Core.TyCon (tyConClass_maybe)-import GHC.Core.DataCon (dataConTyCon)  {- ************************************************************************@@ -653,9 +654,7 @@               -- Easiest thing is to do it all at once, as if all the top-level               -- decls were mutually recursive        ; let top_env = SE { se_subst = Core.mkEmptySubst $-                                        mkInScopeSetBndrs binds-                                      --    mkInScopeSetList $-                                      --  bindersOfBinds binds+                                       mkInScopeSetBndrs binds                           , se_module = this_mod                           , se_rules  = rule_env                           , se_dflags = dflags }@@ -815,9 +814,12 @@     go :: SpecEnv -> [CallInfoSet] -> CoreM (SpecEnv, [CoreRule], [CoreBind])     go env [] = return (env, [], [])     go env (cis : other_calls)-      = do { -- debugTraceMsg (text "specImport {" <+> ppr cis)+      = do {+--             debugTraceMsg (text "specImport {" <+> vcat [ ppr cis+--                                                         , text "callers" <+> ppr callers+--                                                         , text "dict_binds" <+> ppr dict_binds ])            ; (env, rules1, spec_binds1) <- spec_import env callers dict_binds cis-           ; -- debugTraceMsg (text "specImport }" <+> ppr cis)+--           ; debugTraceMsg (text "specImport }" <+> ppr cis)             ; (env, rules2, spec_binds2) <- go env other_calls            ; return (env, rules1 ++ rules2, spec_binds1 ++ spec_binds2) }@@ -834,13 +836,18 @@                      , [CoreBind] )  -- Specialised bindings spec_import env callers dict_binds cis@(CIS fn _)   | isIn "specImport" fn callers-  = return (env, [], [])  -- No warning.  This actually happens all the time-                          -- when specialising a recursive function, because-                          -- the RHS of the specialised function contains a recursive-                          -- call to the original function+  = do {+--         debugTraceMsg (text "specImport1-bad" <+> (ppr fn $$ text "callers" <+> ppr callers))+       ; return (env, [], []) }+    -- No warning.  This actually happens all the time+    -- when specialising a recursive function, because+    -- the RHS of the specialised function contains a recursive+    -- call to the original function    | null good_calls-  = return (env, [], [])+  = do {+--        debugTraceMsg (text "specImport1-no-good" <+> (ppr cis $$ text "dict_binds" <+> ppr dict_binds))+       ; return (env, [], []) }    | Just rhs <- canSpecImport dflags fn   = do {     -- Get rules from the external package state@@ -889,7 +896,10 @@        ; return (env, rules2 ++ rules1, final_binds) }    | otherwise-  = do { tryWarnMissingSpecs dflags callers fn good_calls+  = do {+--         debugTraceMsg (hang (text "specImport1-missed")+--                          2 (vcat [ppr cis, text "can-spec" <+> ppr (canSpecImport dflags fn)]))+       ; tryWarnMissingSpecs dflags callers fn good_calls        ; return (env, [], [])}    where@@ -1510,7 +1520,9 @@         ; (fn4, spec_defns, body_uds1) <- specDefn env body_uds fn3 rhs -       ; let (free_uds, dump_dbs, float_all) = dumpBindUDs [fn4] body_uds1+       ; let can_float_this_one = exprIsTopLevelBindable rhs (idType fn)+                 -- exprIsTopLevelBindable: see Note [Care with unlifted bindings]+             (free_uds, dump_dbs, float_all) = dumpBindUDs can_float_this_one [fn4] body_uds1              all_free_uds                    = free_uds `thenUDs` rhs_uds               pairs = spec_defns ++ [(fn4, rhs')]@@ -1526,10 +1538,8 @@                          = [mkDB $ NonRec b r | (b,r) <- pairs]                            ++ fromOL dump_dbs -             can_float_this_one = exprIsTopLevelBindable rhs (idType fn)-             -- exprIsTopLevelBindable: see Note [Care with unlifted bindings] -       ; if float_all && can_float_this_one then+       ; if float_all then              -- Rather than discard the calls mentioning the bound variables              -- we float this (dictionary) binding along with the others               return ([], body', all_free_uds `snocDictBinds` final_binds)@@ -1564,7 +1574,7 @@                               <- specDefns rec_env uds2 (bndrs2 `zip` rhss)                         ; return (bndrs3, spec_defns3 ++ spec_defns2, uds3) } -       ; let (final_uds, dumped_dbs, float_all) = dumpBindUDs bndrs1 uds3+       ; let (final_uds, dumped_dbs, float_all) = dumpBindUDs True bndrs1 uds3              final_bind = recWithDumpedDicts (spec_defns3 ++ zip bndrs3 rhss')                                              dumped_dbs @@ -1675,7 +1685,8 @@     fn_unf    = realIdUnfolding fn  -- Ignore loop-breaker-ness here     inl_prag  = idInlinePragma fn     inl_act   = inlinePragmaActivation inl_prag-    is_active = isActive (beginPhase inl_act) :: Activation -> Bool+    is_active :: Activation -> Bool+    is_active = isActive (SimplPhaseRange (beginPhase inl_act) (endPhase inl_act))          -- is_active: inl_act is the activation we are going to put in the new          --   SPEC rule; so we want to see if it is covered by another rule with          --   that same activation.@@ -1684,7 +1695,6 @@     dflags    = se_dflags env     this_mod  = se_module env     subst     = se_subst env-    in_scope  = Core.substInScopeSet subst         -- Figure out whether the function has an INLINE pragma         -- See Note [Inline specialisations] @@ -1700,9 +1710,6 @@       | otherwise       = inl_prag -    not_in_scope :: InterestingVarFun-    not_in_scope v = isLocalVar v && not (v `elemInScopeSet` in_scope)-     ----------------------------------------------------------         -- Specialise to one particular call pattern     spec_call :: SpecInfo                         -- Accumulating parameter@@ -1716,48 +1723,35 @@                  mk_extra_dfun_arg bndr | isTyVar bndr = UnspecType                                         | otherwise    = UnspecArg -             -- Find qvars, the type variables to add to the binders for the rule-             -- Namely those free in `ty` that aren't in scope-             -- See (MP2) in Note [Specialising polymorphic dictionaries]-           ; let poly_qvars = scopedSort $ fvVarList $ specArgsFVs not_in_scope call_args-                 subst'     = subst `Core.extendSubstInScopeList` poly_qvars-                              -- Maybe we should clone the poly_qvars telescope?--             -- Any free Ids will have caused the call to be dropped-           ; massertPpr (all isTyCoVar poly_qvars)-                        (ppr fn $$ ppr all_call_args $$ ppr poly_qvars)--           ; (useful, subst'', rule_bndrs, rule_lhs_args, spec_bndrs, dx_binds, spec_args)-                 <- specHeader subst' rhs_bndrs all_call_args-           ; let all_rule_bndrs = poly_qvars ++ rule_bndrs-                 env' = env { se_subst = subst'' }+           ; (useful, subst', rule_bndrs, rule_lhs_args, spec_bndrs, dx_binds, spec_args)+                 <- specHeader subst rhs_bndrs all_call_args+           ; let env' = env { se_subst = subst' }             -- Check for (a) usefulness and (b) not already covered            -- See (SC1) in Note [Specialisations already covered]            ; let all_rules = rules_acc ++ existing_rules                  -- all_rules: we look both in the rules_acc (generated by this invocation                  --   of specCalls), and in existing_rules (passed in to specCalls)-                 already_covered = alreadyCovered env' all_rule_bndrs fn+                 already_covered = alreadyCovered env' rule_bndrs fn                                                   rule_lhs_args is_active all_rules -{-         ; pprTrace "spec_call" (vcat-                [ text "fun:       "  <+> ppr fn-                , text "call info: "  <+> ppr _ci-                , text "useful:    "  <+> ppr useful-                , text "already_covered:"  <+> ppr already_covered-                , text "poly_qvars: " <+> ppr poly_qvars-                , text "useful:    "  <+> ppr useful-                , text "all_rule_bndrs:"  <+> ppr all_rule_bndrs-                , text "rule_lhs_args:"  <+> ppr rule_lhs_args-                , text "spec_bndrs:" <+> ppr spec_bndrs-                , text "dx_binds:"   <+> ppr dx_binds-                , text "spec_args: "  <+> ppr spec_args-                , text "rhs_bndrs"    <+> ppr rhs_bndrs-                , text "rhs_body"     <+> ppr rhs_body-                , text "subst''" <+> ppr subst'' ]) $-             return ()--}+--         ; pprTrace "spec_call" (vcat+--                [ text "fun:       "  <+> ppr fn+--                , text "call info: "  <+> ppr _ci+--                , text "useful:    "  <+> ppr useful+--                , text "already_covered:"  <+> ppr already_covered+--                , text "useful:    "  <+> ppr useful+--                , text "rule_bndrs:"  <+> ppr (sep (map (pprBndr LambdaBind) rule_bndrs))+--                , text "rule_lhs_args:"  <+> ppr rule_lhs_args+--                , text "spec_bndrs:" <+> ppr (sep (map (pprBndr LambdaBind) spec_bndrs))+--                , text "dx_binds:"   <+> ppr dx_binds+--                , text "spec_args: "  <+> ppr spec_args+--                , text "rhs_bndrs"    <+> ppr (sep (map (pprBndr LambdaBind) rhs_bndrs))+--                , text "rhs_body"     <+> ppr rhs_body+--                , text "subst'" <+> ppr subst'+--                ]) $ return () +            ; if not useful          -- No useful specialisation                 || already_covered  -- Useful, but done already              then return spec_acc@@ -1770,23 +1764,13 @@              -- Run the specialiser on the specialised RHS            ; (rhs_body', rhs_uds) <- specExpr env'' rhs_body -{-         ; pprTrace "spec_call2" (vcat-                 [ text "fun:" <+> ppr fn-                 , text "rhs_body':" <+> ppr rhs_body' ]) $-             return ()--}-            -- Make the RHS of the specialised function            ; let spec_rhs_bndrs = spec_bndrs ++ inner_rhs_bndrs'-                 (rhs_uds1, inner_dumped_dbs) = dumpUDs spec_rhs_bndrs rhs_uds-                 (rhs_uds2, outer_dumped_dbs) = dumpUDs poly_qvars (dx_binds `consDictBinds` rhs_uds1)-                 -- dx_binds comes from the arguments to the call, and so can mention-                 -- poly_qvars but no other local binders-                 spec_rhs = mkLams poly_qvars               $-                            wrapDictBindsE outer_dumped_dbs $-                            mkLams spec_rhs_bndrs           $+                 (rhs_uds2, inner_dumped_dbs) = dumpUDs spec_rhs_bndrs $+                                                dx_binds `consDictBinds` rhs_uds+                 spec_rhs = mkLams spec_rhs_bndrs $                             wrapDictBindsE inner_dumped_dbs rhs_body'-                 rule_rhs_args = poly_qvars ++ spec_bndrs+                 rule_rhs_args = spec_bndrs                   -- Maybe add a void arg to the specialised function,                  -- to avoid unlifted bindings@@ -1826,7 +1810,7 @@                  spec_fn_details                    = case idDetails fn of                        JoinId join_arity _ -> JoinId (join_arity - join_arity_decr) Nothing-                       DFunId unary        -> DFunId unary+                       DFunId terminating  -> DFunId terminating                        _                   -> VanillaId             ; spec_fn <- newSpecIdSM (idName fn) spec_fn_ty1 spec_fn_details spec_fn_info@@ -1841,7 +1825,7 @@                                      text "SPEC"                  spec_rule = mkSpecRule dflags this_mod True inl_act-                                    herald fn all_rule_bndrs rule_lhs_args+                                    herald fn rule_bndrs rule_lhs_args                                     (mkVarApps (Var spec_fn) rule_rhs_args1)                  _rule_trace_doc = vcat [ ppr fn <+> dcolon <+> ppr fn_type@@ -1852,8 +1836,11 @@                                        , text "existing" <+> ppr existing_rules                                        ] -           ; -- pprTrace "spec_call: rule" _rule_trace_doc-             return ( spec_rule            : rules_acc+--           ; pprTrace "spec_call: rule" (vcat [ text "rule_bndrs" <+> ppr rule_bndrs+--                                              , text "rule_lhs_args" <+> ppr rule_lhs_args+--                                              , text "all_call_args" <+> ppr all_call_args+--                                              , ppr spec_rule ]) $+           ; return ( spec_rule            : rules_acc                     , (spec_fn, spec_rhs1) : pairs_acc                     , rhs_uds2 `thenUDs` uds_acc                     ) } }@@ -2000,7 +1987,17 @@ the non-top-level in-scope binders are) and rare (since the binding must satisfy Note [Core let-can-float invariant] in GHC.Core). +Arguably we'd be better off if we had left that `x` in the RHS of `n`, thus+    f x = let n::Natural = let x::ByteArray# = <some literal> in+                           NB x+          in wombat @192827 (n |> co)+Now we could float `n` happily.  But that's in conflict with exposing the `NB`+data constructor in the body of the `let`, so I'm leaving this unresolved. +Another case came up in #26682, where the binding had an unlifted sum type+(# Word# | ByteArray# #), itself arising from an UNPACK pragma.  Test case+T26682.+ Note [Specialising Calls] ~~~~~~~~~~~~~~~~~~~~~~~~~ Suppose we have a function with a complicated type:@@ -2059,49 +2056,22 @@ additionally that 'x' isn't captured by this rule --- we bind only enough etas in order to capture all of the *specialised* arguments. -Note [Drop dead args from specialisations]-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-When specialising a function, it’s possible some of the arguments may-actually be dead. For example, consider:+Note [Do not drop dead args from specialisations]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+When specialising a function, some of its arguments may be dead. For example      f :: forall a. () -> Show a => a -> String     f x y = show y ++ "!" -We might generate the following CallInfo for `f @Int`:--    [SpecType Int, UnspecArg, SpecDict $dShowInt, UnspecArg]--Normally we’d include both the x and y arguments in the-specialisation, since we’re not specialising on either of them. But-that’s silly, since x is actually unused! So we might as well drop it-in the specialisation:--    $sf :: Int -> String-    $sf y = show y ++ "!"--    {-# RULE "SPEC f @Int" forall x. f @Int x $dShow = $sf #-}--This doesn’t save us much, since the arg would be removed later by-worker/wrapper, anyway, but it’s easy to do.--Wrinkles--* Note that we only drop dead arguments if:-    1. We don’t specialise on them.-    2. They come before an argument we do specialise on.-  Doing the latter would require eta-expanding the RULE, which could-  make it match less often, so it’s not worth it. Doing the former could-  be more useful --- it would stop us from generating pointless-  specialisations --- but it’s more involved to implement and unclear if-  it actually provides much benefit in practice.--* If the function has a stable unfolding, specHeader has to come up with-  arguments to pass to that stable unfolding, when building the stable-  unfolding of the specialised function: this is the last field in specHeader's-  big result tuple.+gives the CallInfo [SpecType Int, UnspecArg, SpecDict $dShowInt, UnspecArg]+for `f @Int`, in which `x` is dead. We used to drop such an argument from the+specialisation and pass an absent filler in its place. -  The right thing to do is to produce a LitRubbish; it should rapidly-  disappear.  Rather like GHC.Core.Opt.WorkWrap.Utils.mk_absent_let.+We no longer do so, because the filler is applied to the function's stable+unfolding template rather than to its optimised RHS, and the two may differ:+the argument can be dead in the RHS and not in the template. The specialised+function's unfolding then contains the filler, and any call site that inlines+it evaluates the error thunk. See #27703 for an instance of how this goes wrong.  Note [Specialisation modulo dictionary selectors] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~@@ -2166,8 +2136,7 @@     RULE "SPEC f @Int" forall x [Occ=Dead].       f @Int x $dShow = $sf -and Core Lint complains, even though x only appears on the LHS (due to-Note [Drop dead args from specialisations]).+and Core Lint complains, even though x only appears on the LHS.  Why is that a Lint error? Because the arguments on the LHS of a rule are syntactically expressions, not patterns, so Lint treats the@@ -2647,13 +2616,23 @@ -- 'a->T1', as well as a LHS argument for the resulting RULE and unfolding -- details. specHeader subst (bndr:bndrs) (SpecType ty : args)-  = do { let subst1 = Core.extendTvSubst subst bndr ty-       ; (useful, subst2, rule_bs, rule_args, spec_bs, dx, spec_args)-             <- specHeader subst1 bndrs args-       ; pure ( useful, subst2-              , rule_bs,     Type ty : rule_args-              , spec_bs, dx, Type ty : spec_args ) }+  = do { -- Find free_tvs, the type variables to add to the binders for the rule+         -- Namely those free in `ty` that aren't in scope+         -- See (MP2) in Note [Specialising polymorphic dictionaries]+         let in_scope = Core.substInScopeSet subst+             not_in_scope tv = not (tv `elemInScopeSet` in_scope)+             free_tvs = scopedSort $ fvVarList $+                        filterFV not_in_scope  $+                        tyCoFVsOfType ty+             subst1 = subst `Core.extendSubstInScopeList` free_tvs +       ; let subst2 = Core.extendTvSubst subst1 bndr ty+       ; (useful, subst3, rule_bs, rule_args, spec_bs, dx, spec_args)+             <- specHeader subst2 bndrs args+       ; pure ( useful, subst3+              , free_tvs ++ rule_bs,     Type ty : rule_args+              , free_tvs ++ spec_bs, dx, Type ty : spec_args ) }+ -- Next we have a type that we don't want to specialise. We need to perform -- a substitution on it (in case the type refers to 'a'). Additionally, we need -- to produce a binder, LHS argument and RHS argument for the resulting rule,@@ -2667,20 +2646,21 @@               , bndr' : rule_bs,     ty_e' : rule_es               , bndr' : spec_bs, dx, ty_e' : spec_args ) } -specHeader subst (bndr:bndrs) (_ : args)-  | isDeadBinder bndr-  , let (subst1, bndr') = Core.substBndr subst (zapIdOccInfo bndr)-  , Just rubbish_lit <- mkLitRubbish (idType bndr')-  = -- See Note [Drop dead args from specialisations]-    do { (useful, subst2, rule_bs, rule_es, spec_bs, dx, spec_args) <- specHeader subst1 bndrs args-       ; pure ( useful, subst2-              , bndr' : rule_bs, Var bndr'   : rule_es-              , spec_bs,     dx, rubbish_lit : spec_args ) }- -- Next we want to specialise the 'Eq a' dict away. We need to construct -- a wildcard binder to match the dictionary (See Note [Specialising Calls] for -- the nitty-gritty), as a LHS rule and unfolding details. specHeader subst (bndr:bndrs) (SpecDict dict_arg : args)+  | let in_scope = getInScopeVars (substInScopeSet subst)+        bad_dict_fv v = isLocalVar v && not (v `elemVarSet` in_scope)+  , not $ isEmptyVarSet $ exprSomeFreeVars bad_dict_fv dict_arg+  = -- Do not specialise if `dict_arg` has any free vars that are /not/ in scope+    -- See Note [Weird special case for SpecDict]+    -- We add a warnPprTrace because this should be super-rare,+    -- so if it starts happening we'd like to know.+    warnPprTrace True "Specialise: weird dictionary with free type variable" (ppr dict_arg) $+    specHeader subst (bndr:bndrs) (UnspecArg : args)++  | otherwise   = do { -- Make up a fresh binder to use in the RULE          -- It might turn into a dict binding (via bindAuxiliaryDict) which we          -- then float, so we use cloneIdBndr to get a completely fresh binder@@ -2691,7 +2671,8 @@          -- Extend the substitution to map bndr :-> dict_arg, for use in the RHS        ; let (subst2, dx_bind, spec_dict) = bindAuxiliaryDict subst1 bndr bndr' dict_arg -       ; (_, subst3, rule_bs, rule_es, spec_bs, dx, spec_args) <- specHeader subst2 bndrs args+       ; (_, subst3, rule_bs, rule_es, spec_bs, dx, spec_args)+             <- specHeader subst2 bndrs args         ; let dx' = case dx_bind of { Nothing -> dx; Just d -> d : dx }        ; pure ( True, subst3      -- Ha!  A useful specialisation!@@ -2709,7 +2690,8 @@ specHeader subst (bndr:bndrs) (UnspecArg : args)   = do { let (subst1, bndr') = Core.substBndr subst (zapIdOccInfo bndr)                  -- zapIdOccInfo: see Note [Zap occ info in rule binders]-       ; (useful, subst2, rule_bs, rule_es, spec_bs, dx, spec_args) <- specHeader subst1 bndrs args+       ; (useful, subst2, rule_bs, rule_es, spec_bs, dx, spec_args)+             <- specHeader subst1 bndrs args         ; let dummy_arg = varToCoreExpr bndr'                -- dummy_arg is usually just (Var bndr),@@ -2736,7 +2718,7 @@   -- don’t bother creating a new dict binding; just substitute   | exprIsTrivial dict_arg   , let subst' = Core.extendSubst subst orig_dict_id dict_arg-  = -- pprTrace "bindAuxiliaryDict:trivial" (ppr orig_dict_id <+> ppr dict_id) $+  = -- pprTrace "bindAuxiliaryDict:trivial" (ppr orig_dict_id <+> ppr dict_arg) $     (subst', Nothing, dict_arg)    | otherwise  -- Non-trivial dictionary arg; make an auxiliary binding@@ -2954,13 +2936,15 @@ is a lot of hard work for a very strange case.  So we simply refrain from specialising in this case; hence the guard-   allVarSet (`elemInScopeSet` in_scope) (exprFreeVars d)-in the SpecDict cased of specHeader.+   not $ isEmptyVarSet $ exprSomeFreeVars bad_dict_fv dict_arg+in the SpecDict case of `specHeader`. -How did this strange polymorphic mkD arise in the first place?-From GHC.Core.Opt.Utils.abstractFloats, which was abstracting-over too many type variables. But that too is now fixed;-see Note [Which type variables to abstract over] in that module.+How did this strange polymorphic mkD arise in the first place?  From+GHC.Core.Opt.Simplify.Utils.abstractFloats, which was abstracting over too many type+variables. But that too is now fixed; see Note [Which type variables to abstract+over] in that module.  So we don't actually have a Haskell source program that+triggers it (see #27629) -- only test T27629 that uses a plugin to inject a strange+definition. -}  instance Outputable DictBind where@@ -3032,7 +3016,8 @@  instance Outputable CallInfo where   ppr (CI { ci_key = key, ci_fvs = _fvs })-    = text "CI" <> braces (sep (map ppr key))+    = text "CI" <> braces (text "fvs" <+> ppr _fvs+                           $$ sep (map ppr key))  unionCalls :: CallDetails -> CallDetails -> CallDetails unionCalls c1 c2 = plusDVarEnv_C unionCallInfoSet c1 c2@@ -3144,8 +3129,8 @@ -- This is a subtle and important function -- See Note [Interesting dictionary arguments] interestingDict env (Var v)  -- See (ID3) and (ID5)+  -- (ID6.a) Might fail for loop breaker dicts but that seems fine.   | Just rhs <- maybeUnfoldingTemplate (idUnfolding v)-  -- Might fail for loop breaker dicts but that seems fine.   = interestingDict env rhs  interestingDict env arg  -- Main Plan: use exprIsConApp_maybe@@ -3160,9 +3145,9 @@        , isIPClass cls      -- See (ID5)        -> False -       -- Otherwise we are unwrapping a unary type class+       -- Shouldn't happen.        | otherwise-       -> exprIsHNF arg   -- See (ID7)+       -> pprTraceDebug "shouldn't happen anymore" (ppr arg) $ exprIsHNF arg -- See (ID7)    | Just (_, _, data_con, _tys, args) <- exprIsConApp_maybe in_scope_env arg   , Just cls <- tyConClass_maybe (dataConTyCon data_con)@@ -3176,7 +3161,8 @@   where     arg_ty                  = exprType arg     definitely_not_ip_like  = not (couldBeIPLike arg_ty)-    in_scope_env = ISE (substInScopeSet $ se_subst env) realIdUnfolding+    -- idUnfolding rather than realIdUnfolding: See (ID6.a)+    in_scope_env = ISE (substInScopeSet $ se_subst env) idUnfolding  {- Note [Ticks on applications] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~@@ -3287,12 +3273,28 @@    in point is constraint tuples (% d1, .., dn %); a constraint N-tuple is a class    with N superclasses and no methods. -(ID7) A unary (single-method) class is currently represented by (meth |> co).  We-   will unwrap the cast (see (ID5)) and then want to reply "yes" if the method-   has any struture.  We rather arbitrarily use `exprIsHNF` for this.  (We plan a-   new story for unary classes, see #23109, and this special case will become-   irrelevant.)+(ID6.a) If we deal with a recursive dictionary as in #27705 we want to avoid+    infinite recursion while recursing into superclasses. +    For example we might have:++    class D1 a => D2 a+    class D2 a => D1 a++  The primary concern is that we want to avoid looping on recursive instances.+  We can achieve this by simply not looking through loop breakers by using idUnfolding+  rather than realIdUnfolding.++  It's possible that this prevents specialization of edge cases that have loop breakers+  in their recursive loop. But even if we can find a dictionary like this the simplifier+  won't look through loopbreaker dictionaries either killing any potential benefit.+  So while we could handle this case via a already-seen set or fuel we simply don't bother+  for now.++(ID7) A unary (single-method) class is currently handled by the same path as regular dicts+   since they are represented by faking a regular Dictionary.+   See Note [Unary class magic] for the details.+ (ID8) Sadly, if `exprIsConApp_maybe` says Nothing, we still want to treat a    non-trivial argument as interesting. In T19695 we have this:       askParams :: Monad m => blah@@ -3448,38 +3450,49 @@  ---------------------- dumpUDs :: [CoreBndr] -> UsageDetails -> (UsageDetails, OrdList DictBind)--- Used at a lambda or case binder; just dump anything mentioning the binder+-- Used at binder; just dump anything mentioning the binder dumpUDs bndrs uds@(MkUD { ud_binds = orig_dbs, ud_calls = orig_calls })   | null bndrs = (uds, nilOL)  -- Common in case alternatives   | otherwise  = -- pprTrace "dumpUDs" (vcat-                 --    [ text "bndrs" <+> ppr bndrs-                 --    , text "uds" <+> ppr uds-                 --    , text "free_uds" <+> ppr free_uds-                 --    , text "dump-dbs" <+> ppr dump_dbs ]) $+                 --   [ text "bndrs" <+> ppr bndrs+                 --   , text "uds" <+> ppr uds+                 --   , text "free_uds" <+> ppr free_uds+                 --   , text "dump_dbs" <+> ppr dump_dbs ]) $                  (free_uds, dump_dbs)   where     free_uds = uds { ud_binds = free_dbs, ud_calls = free_calls }     bndr_set = mkVarSet bndrs     (free_dbs, dump_dbs, dump_set) = splitDictBinds orig_dbs bndr_set-    free_calls = deleteCallsMentioning dump_set $   -- Drop calls mentioning bndr_set on the floor-                 deleteCallsFor bndrs orig_calls    -- Discard calls for bndr_set; there should be-                                                    -- no calls for any of the dicts in dump_dbs -dumpBindUDs :: [CoreBndr] -> UsageDetails -> (UsageDetails, OrdList DictBind, Bool)+    -- Delete calls:+    --   * For any binder in `bndrs`+    --   * That mention a dictionary bound in `dump_set`+    -- These variables aren't in scope "above" the binding and the `dump_dbs`,+    -- so no call should mention them.  (See #26682.)+    free_calls = deleteCallsMentioning dump_set $+                 deleteCallsFor bndrs orig_calls++dumpBindUDs :: Bool   -- Main binding can float to top+            -> [CoreBndr] -> UsageDetails+            -> (UsageDetails, OrdList DictBind, Bool) -- Used at a let(rec) binding.--- We return a boolean indicating whether the binding itself is mentioned,--- directly or indirectly, by any of the ud_calls; in that case we want to--- float the binding itself;--- See Note [Floated dictionary bindings]-dumpBindUDs bndrs (MkUD { ud_binds = orig_dbs, ud_calls = orig_calls })-  = -- pprTrace "dumpBindUDs" (ppr bndrs $$ ppr free_uds $$ ppr dump_dbs $$ ppr float_all) $-    (free_uds, dump_dbs, float_all)+-- We return a boolean indicating whether the binding itself+--    is mentioned, directly or indirectly, by any of the ud_calls;+--    in that case we want to float the binding itself.+--    See Note [Floated dictionary bindings]+-- If the boolean is True, then the returned ud_calls can mention `bndrs`;+-- if False, then returned ud_calls must not mention `bndrs`+dumpBindUDs can_float_bind bndrs (MkUD { ud_binds = orig_dbs, ud_calls = orig_calls })+  = ( MkUD { ud_binds = free_dbs, ud_calls = free_calls2 }+    , dump_dbs+    , can_float_bind && calls_mention_bndrs )   where-    free_uds = MkUD { ud_binds = free_dbs, ud_calls = free_calls }     bndr_set = mkVarSet bndrs     (free_dbs, dump_dbs, dump_set) = splitDictBinds orig_dbs bndr_set-    free_calls = deleteCallsFor bndrs orig_calls-    float_all = dump_set `intersectsVarSet` callDetailsFVs free_calls+    free_calls1 = deleteCallsFor bndrs orig_calls+    calls_mention_bndrs = dump_set `intersectsVarSet` callDetailsFVs free_calls1+    free_calls2 | can_float_bind = free_calls1+                | otherwise      = deleteCallsMentioning dump_set free_calls1  callsForMe :: Id -> UsageDetails -> (UsageDetails, [CallInfo]) callsForMe fn uds@MkUD { ud_binds = orig_dbs, ud_calls = orig_calls }
GHC/Core/Opt/WorkWrap.hs view
@@ -176,8 +176,9 @@ mischief.)  Notice that we refrain from w/w'ing an INLINE function even if it is-in a recursive group.  It might not be the loop breaker.  (We could-test for loop-breaker-hood, but I'm not sure that ever matters.)+in a recursive group.  It might not be the loop breaker.  (We used to+test for loop-breaker-hood, but see (CWW4) in Note [Cast worker/wrapper]+in GHC.Core.Opt.Simplify.Iteration.)  Note [Worker/wrapper for INLINABLE functions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~@@ -549,7 +550,7 @@   -- See Note [Drop absent bindings]   | isAbsDmd (demandInfo fn_info)   , not (isJoinId fn_id)-  , Just filler <- mkAbsentFiller ww_opts fn_id NotMarkedStrict+  , Just filler <- mkAbsentFiller (wo_module ww_opts) fn_id NotMarkedStrict   = return [(new_fn_id, filler)]    -- See Note [Don't w/w INLINE things]@@ -910,9 +911,9 @@                  , inl_rule   = rule_info }  -- RuleMatchInfo is (and must be) unaffected   where     -- See Note [Wrapper activation]-    wrapper_phase = foldr (laterPhase . get_rule_phase) earliest_inline_phase rules-    earliest_inline_phase = beginPhase fn_act `laterPhase` nextPhase InitialPhase-          -- laterPhase (nextPhase InitialPhase) is a temporary hack+    wrapper_phase = foldr (latestPhase . get_rule_phase) earliest_inline_phase rules+    earliest_inline_phase = beginPhase fn_act `latestPhase` nextPhase InitialPhase+          -- latestPhase (nextPhase InitialPhase) is a temporary hack           -- to inline no earlier than phase 2.  I got regressions in           -- 'mate', due to changes in full laziness due to Note [Case           -- MFEs], when I did earlier inlining.@@ -921,10 +922,8 @@     -- The phase /after/ the rule is first active     get_rule_phase rule = nextPhase (beginPhase (ruleActivation rule)) -{--Note [Demand on the worker]-~~~~~~~~~~~~~~~~~~~~~~~~~~~-+{- Note [Demand on the worker]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If the original function is called once, according to its demand info, then so is the worker. This is important so that the occurrence analyser can attach OneShot annotations to the worker’s lambda binders.
GHC/Core/Opt/WorkWrap/Utils.hs view
@@ -30,10 +30,9 @@ import GHC.Core.Type import GHC.Core.Multiplicity import GHC.Core.Coercion-import GHC.Core.Predicate( isDictTy ) import GHC.Core.Reduction import GHC.Core.FamInstEnv-import GHC.Core.Predicate( isEqualityClass )+import GHC.Core.Predicate( isEqualityClass, isPredTy ) import GHC.Core.TyCon import GHC.Core.TyCon.Set import GHC.Core.TyCon.RecWalk@@ -1031,7 +1030,7 @@     _ | isTyVar arg -> do_nothing      DropAbsent-      | Just absent_filler <- mkAbsentFiller opts arg str_mark+      | Just absent_filler <- mkAbsentFiller (wo_module opts) arg str_mark          -- Absent case.  Drop the argument from the worker.          -- We can't always handle absence for arbitrary          -- unlifted types, so we need to choose just the cases we can@@ -1102,14 +1101,20 @@ -- -- If @mkAbsentFiller _ id == Just e@, then @e@ is an absent filler with the -- same type as @id@. Otherwise, no suitable filler could be found.-mkAbsentFiller :: WwOpts -> Id -> StrictnessMark -> Maybe CoreExpr-mkAbsentFiller opts arg str+mkAbsentFiller :: Module -> Id -> StrictnessMark -> Maybe CoreExpr+mkAbsentFiller mod arg str+  -- We never make a filler for a constraint type: it might be speculatively+  -- evaluated or have a field projected out of it.+  -- See (AF4) in Note [Absent fillers], and+  -- Note [Don't make fillers for constraint types].+  | isPredTy arg_ty+  = Nothing+   -- The lifted case: bind 'absentError'. See (AF1) in Note [Absent fillers]   -- We want to use this case if possible, because we get a nice runtime panic message   -- if we are wrong (like we were in #11126).  Otherwise we fall through to the   -- less-desirable mkLitRubbish case.   | mightBeLiftedType arg_ty-  , not (isDictTy arg_ty)                 -- See (AF4) in Note [Absent fillers]   , not (isStrictDmd (idDemandInfo arg))  -- See (AF2)   , not (isMarkedStrict str)              --    in Note [Absent fillers]   = Just (mkAbsentErrorApp arg_ty msg)@@ -1136,7 +1141,7 @@               -- will have different lengths and hence different costs for               -- the inliner leading to different inlining.               -- See also Note [Unique Determinism] in GHC.Types.Unique-    file_msg = text "In module" <+> quotes (ppr $ wo_module opts)+    file_msg = text "In module" <+> quotes (ppr mod)  {- Note [Worker/wrapper for Strictness and Absence] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~@@ -1329,27 +1334,8 @@      have to be representation monomorphic. But in the future, we might allow      levity polymorphism, e.g. a polymorphic levity variable in 'BoxedRep'. -(AF4) Consider (#24934)-         f :: (a~b) => blah {-# INLINE f #-}-         f d x = case eq_sel d of co -> body-     In #24934 it turned out that `co` was unused; and we discarded the-     entire case-scrutinisation via the `exprOkToDiscard` test in-     `GHC.Core.Opt.Simplify.Iteration.rebuildCase`.  So now `d` is absent.-     But in the /unfolding/ for some reason we did not discard the `case`;-     so when we inline `f` we end up evaluating that `d` argument.  So we had-     better not replace it with an error thunk!--     The root of it is this: `exprOkToDiscard` assumes that a dictionary is-     non-bottom (Note [exprOkForSpeculation and type classes]); but then we replace-     the (a~b) dictionary with an error thunk, breaking the invariant that every-     dictionary is non-bottom.  (If -XDictsStrict is on, the invariant is even-     more important.)--     Simple solution: never use an error thunk for a dictionary; instead fall-     through to mkRubbishLit.  (The only downside is that we lose the compiler-     debugging advantages of (AF1).)--     This is quite delicate.+(AF4) We never make an absent filler for a constraint type.+      See Note [Don't make fillers for constraint types].  While (AF1) and (AF2) are simply an optimisation in terms of compiler debugging experience, (AF3) should be irrelevant in most programs, if not all.@@ -1370,6 +1356,70 @@        ...f (MkT a (absentError Int# "blah"))...    because `MkT` is strict in its Int# argument, so we get an absentError    exception when we shouldn't.  Very annoying!++Note [Don't make fillers for constraint types]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+We never make absent fillers for constraint types (see `isPredTy`).+Here's why.++GHC relies on a dictionary value never being bottom (see+Note [NON-BOTTOM-DICTS invariant] in GHC.Core).  GHC uses "speculation" to+evaluate guaranteed-non-bottom values: see+  Note [Speculative evaluation] in GHC.CoreToStg.Prep.+  Note [exprOkForSpeculation and type classes] in GHC.Core.Utils++This speculative evaluation is fundamentally incompatible with replacing a+dictionary with an absent filler.  Attempts to to do so gave rise to a+succession of bugs including:++  * #24934: we evaluated an absent dictionary+  * #25924: we selected a superclass from an absent dictionary+  * #27627: we still got it wrong for unary classes+  * Test T27627f: type families complicate the picture++It's surprisingly subtle.++* Consider (#27627)+    class Eq a => UC a where {}++    let u :: UC Int           -- UC Int is a "non-terminating type"+        u = error "Absent"+    let e :: Eq Int           -- Eq Int is a "terminating type"+        e = $p1UC u++  We clearly don't want to make an absent filler for `e`, because we'll speculatively+  evaluate it.  But if we speculatively evalutate `e` that will force `u`, so we+  must not make an absent filler for `u` either!!++* Type families complicate things too. Consider+     type family F a :: Constraint+     type instance F W = TC W++     a :: F W => Int -> Int      -- (F W) argument is absent++  Here `(F W)` doesn't look like a /dictionary/ type, becuase it's a type-family+  application; see test `T27627f`.++TL;DR: we play safe: we never make an absent filler for any /constraint-kinded/ type,+using `isPredTy` to decide.++  * `mkAbsentFiller` returns `Nothing` for any constraint type, so worker/wrapper+    keeps the real argument.++  * `Specialise.specHeader` calls `mkAbsentFiller` too, so it likewise keeps the+    dead dictionary argument rather than dropping it for a filler.++Prior failed approaches++We used to paper over this. !13233 replaced the error thunk for an absent+dictionary with a rubbish literal, so that it could at least be evaluated+without complaint. But #25924 showed that this is not enough, because we do not+only evaluate the absent dictionary, we also select a superclass from it.++We could instead teach speculation to leave absent bindings alone, and we do+that too (see Note [Speculative evaluation] in GHC.CoreToStg.Prep). But that is+not a guarantee. After optimisation a binding that holds an absent filler may no+longer be marked absent, so we cannot rely on the demand to protect us.  Note [Unboxing through unboxed tuples] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
GHC/Core/Rules.hs view
@@ -1902,7 +1902,7 @@                  -> (Id -> [CoreRule])          -- ^ Rules for an Id                  -> CoreProgram                 -- ^ Bindings to check in                  -> SDoc                        -- ^ Resulting check message-ruleCheckProgram ropts phase rule_pat rules binds+ruleCheckProgram ropts curr_phase rule_pat rules binds   | isEmptyBag results   = text "Rule check results: no rule application sites"   | otherwise@@ -1912,9 +1912,9 @@          ]   where     line = text (replicate 20 '-')-    env = RuleCheckEnv { rc_is_active = isActive phase-                       , rc_id_unf    = idUnfolding     -- Not quite right-                                                        -- Should use activeUnfolding+    is_active = isActiveInPhase curr_phase+    env = RuleCheckEnv { rc_is_active = is_active+                       , rc_id_unf    = whenActiveUnfoldingFun is_active                        , rc_pattern   = rule_pat                        , rc_rules     = rules                        , rc_ropts     = ropts
GHC/Core/TyCon.hs view
@@ -47,7 +47,7 @@          -- ** Predicates on TyCons         isAlgTyCon, isVanillaAlgTyCon, isClassTyCon,-        isUnaryClassTyCon, isUnaryClassTyCon_maybe,+        isUnaryClassTyCon, isUnaryClassTyCon_maybe, isTerminatingTyCon,         isFamInstTyCon,         isPrimTyCon,         isTupleTyCon, isUnboxedTupleTyCon, isBoxedTupleTyCon,@@ -1489,7 +1489,8 @@  (UCM3) Unlike non-unary classes, a value of type (C ty), where `C` is a unary    class, might be bottom, because it is represented by the method type alone.-   See GHC.Core.Type.isTerminatingType.+   See GHC.Core.Type.isTerminatingType, and Note [NON-BOTTOM-DICTS invariant]+   in GHC.Core     Similarly in exprOkForSpeculation/exprOkToDiscard/exprOkForSpecEval,    in GHC.Core.Utils.  In the utility funcion `app_ok` we need a special@@ -1569,7 +1570,21 @@   a black hole when rehydrating interface the interface file. Easiest just to   store the bit!  See `ifUnary` in GHC.Iface.Synatax.IfaceClassBody. +(UCM13) In Core, a case expression must never pattern-match on a unary class+  data constructor (#27071). Since the constructor is erased at runtime, the+  only valid form is: +      case d of bndr { DEFAULT -> ...bndr... }++  See (DALT3) Note [DataAlt restrictions] in GHC.Core.++  Generally, class dictionaries are only taken apart by the method+  selectors, which are never inlined; see Note [ClassOp/DFun selection]+  in GHC.Tc.TyCl.Instance. However the demand analyser can add `seq` forcing+  on strict arguments (see Note [Which Ids should be strictified] in+  GHC.Core.Utils), so we must be careful not to "fill in" the DEFAULT to mention+  the data constructor; see GHC.Core.Utils.refineDefaultAlt.+ Note [Representing unary classes with newtypes: bad, bad, bad] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In the past we represented a unary class with a newtype, but that led to@@ -2935,6 +2950,16 @@     True   | otherwise   = False++isTerminatingTyCon :: TyCon -> Bool+-- ^ True <=> a value of type (T t1..tn), where `T` is this TyCon, cannot be bottom.+-- The only TyCons that satisfy `isTerminatingTyCon` are non-unary class TyCons.+-- See (UCM3) in Note [Unary class magic], and+-- Note [NON-BOTTOM-DICTS invariant] in GHC.Core.+-- An AbstractTyCon returns False: it comes from an hs-boot file, and the real+-- declaration may turn out to be a unary class. See (NBD2) in that Note.+isTerminatingTyCon tc = isClassTyCon tc && not (isUnaryClassTyCon tc)+                                        && not (isAbstractTyCon tc)  isUnaryClassTyCon_maybe :: TyCon -> Maybe (Class, DataCon) isUnaryClassTyCon_maybe (TyCon { tyConDetails = details })
GHC/Core/Type.hs view
@@ -1948,16 +1948,31 @@    | otherwise = False --- | Is this a function or forall?+-- | Is this type a @FunTy@ or a @ForAllTy@, after expanding type synonyms?+--+-- Does not look through newtypes nor reduce type family applications. isPiTy :: Type -> Bool isPiTy ty = case coreFullView ty of   ForAllTy {} -> True   FunTy {}    -> True   _           -> False --- | Is this a function?--- Note: `forall {b}. Show b => b -> IO b` will not be considered a function by this function.---       It would merely be a forall wrapping a function type.+-- | Is this type a function type (e.g. @X -> Y@ or @X => Y@),+-- after expanding type synonyms?+--+-- Note:+--+--  - Does not look through newtypes, so 'isFunTy' is 'False' for @IO ()@,+--    despite the latter being operationally a function (after expanding newtypes).+--  - Does not reduce type family applications, so 'isFunTy' is 'False' for+--    @Id (Int -> Bool)@ (where 'Id' is the identity type family).+--  - Does not consider @ForAllTy@ to be a function type (even when the argument+--    is a required argument), nor does it look through foralls.+--    Hence both 'isFunTy' is 'False' for both @forall b. Show b => b -> b@+--    and for @forall a -> Int@.+--+-- See also 'mightBeFunTy', when you want to know whether something could+-- be a function (taking a value argument) at runtime. isFunTy :: Type -> Bool isFunTy ty   | FunTy {} <- coreFullView ty = True@@ -2487,9 +2502,7 @@ -- NB: unlifted types are not terminating types! --     e.g. you can write a term (loop 1)::Int# that diverges. isTerminatingType ty = case tyConAppTyCon_maybe ty of-    Just tc -> isClassTyCon tc && not (isUnaryClassTyCon tc)-               -- A non-unary class TyCon is terminating-               -- See (UCM3) in Note [Unary class magic] in GHC.Core.TyCon+    Just tc -> isTerminatingTyCon tc     _       -> False  isPrimitiveType :: Type -> Bool
GHC/Core/Unfold.hs view
@@ -776,22 +776,28 @@  classOpSize :: UnfoldingOpts -> Class -> [Id] -> [CoreExpr] -> ExprSize -- See Note [Conlike is interesting]-classOpSize opts cls top_args args-  | isUnaryClass cls-  = sizeZero   -- See (UCM4) in Note [Unary class magic] in GHC.Core.TyCon-  | otherwise-  = case args of-       []                -> sizeZero-       (arg1:other_args) -> SizeIs (size other_args) (arg_discount arg1) 0+classOpSize _opts _cls _top_args []+  = sizeZero   -- A non-applied classop+classOpSize opts cls top_args (dict_arg:other_val_args)+  = SizeIs size (arg_discount dict_arg) 0   where-    size other_args = 20 + (10 * length other_args)+    size | isUnaryClass cls = 0    -- See (UCM4) in Note [Unary class magic] in GHC.Core.TyCon+         | otherwise        = 20 + (10 * length other_val_args)      -- If the class op is scrutinising a lambda bound dictionary then     -- give it a discount, to encourage the inlining of this function-    -- The actual discount is rather arbitrarily chosen-    arg_discount (Var dict) | dict `elem` top_args-                   = unitBag (dict, unfoldingDictDiscount opts)-    arg_discount _ = emptyBag+    arg_discount (Cast arg _co)                    = arg_discount arg+    arg_discount (Var dict) | dict `elem` top_args = unitBag (dict, dict_discount)+    arg_discount _                                 = emptyBag++    -- If we have (class-op d arg1 .. argn) then it's super-good to inline+    -- to expose `d`; not only can we do the dictionary selection+    -- (class-op d), but that will likely expose a lambda which we can then+    -- apply.  In that case (n > 0), we add `unfoldingFunAppDiscount`.+    -- See the discussion on #26831, esp "Delicate inlining".+    dict_discount+      | null other_val_args = unfoldingDictDiscount opts+      | otherwise           = unfoldingDictDiscount opts + unfoldingFunAppDiscount opts  -- | The size of a function call callSize
GHC/Core/Utils.hs view
@@ -11,6 +11,7 @@         -- * Constructing expressions         mkCast, mkCastMCo, mkPiMCo,         mkTick, mkTicks, mkTickNoHNF, tickHNFArgs,+        mkTickCpe,         bindNonRec, needsCaseBinding, needsCaseBindingL,         mkAltExpr, mkDefaultCase, mkSingleAltCase, @@ -19,6 +20,7 @@         mergeAlts, mergeCaseAlts, trimConArgs,         filterAlts, combineIdenticalAlts, refineDefaultAlt,         scaleAltsBy,+        BinderSwapDecision(..), scrutOkForBinderSwap,          -- * Properties of expressions         exprType, coreAltType, coreAltsType,@@ -72,7 +74,7 @@  import GHC.Core import GHC.Core.Ppr-import GHC.Core.FVs( bindFreeVars )+import GHC.Core.FVs( exprFreeVars, bindFreeVars ) import GHC.Core.DataCon import GHC.Core.Type as Type import GHC.Core.Predicate( isEqPred )@@ -100,7 +102,7 @@ import GHC.Types.Unique import GHC.Types.Unique.Set import GHC.Types.Demand-import GHC.Types.RepType (isZeroBitTy)+import GHC.Types.RepType (isZeroBitTy, mightBeFunTy)  import GHC.Data.FastString import GHC.Data.Maybe@@ -112,12 +114,12 @@ import GHC.Utils.Panic import GHC.Utils.Misc +import Control.Monad       ( guard ) import Data.ByteString     ( ByteString ) import Data.Function       ( on ) import Data.List           ( sort, sortBy, partition, zipWith4, mapAccumL ) import qualified Data.List as Partial ( init, last ) import Data.Ord            ( comparing )-import Control.Monad       ( guard ) import qualified Data.Set as Set  {-@@ -252,7 +254,7 @@  mkCastMCo :: CoreExpr -> MCoercionR -> CoreExpr mkCastMCo e MRefl    = e-mkCastMCo e (MCo co) = Cast e co+mkCastMCo e (MCo co) = mkCast e co   -- We are careful to use (MCo co) only when co is not reflexive   -- Hence (Cast e co) rather than (mkCast e co) @@ -303,40 +305,52 @@ -- | Wraps the given expression in the source annotation, dropping the -- annotation if possible. mkTick :: CoreTickish -> CoreExpr -> CoreExpr-mkTick t orig_expr = mkTick' id id orig_expr+mkTick = mk_tick False++-- | A version of 'mkTick' that preserves ANF, for use in Core Prep.+--+-- See Note [mkTick breaks ANF] in GHC.CoreToStg.Prep.+mkTickCpe :: CoreTickish -> CoreExpr -> CoreExpr+mkTickCpe = mk_tick True++-- | Internal function used to define both 'mkTick' and 'mkTickCpe'+-- without duplication.+mk_tick :: Bool -> CoreTickish -> CoreExpr -> CoreExpr+mk_tick preserve_anf t orig_expr = mkTick' id orig_expr  where   -- Some ticks (cost-centres) can be split in two, with the   -- non-counting part having laxer placement properties.   canSplit = tickishCanSplit t && tickishPlace (mkNoCount t) /= tickishPlace t+   -- mkTick' handles floating of ticks *into* the expression.-  -- In this function, `top` is applied after adding the tick, and `rest` before.-  -- This will result in applications that look like (top $ Tick t $ rest expr).-  -- If we want to push the tick deeper, we pre-compose `top` with a function-  -- adding the tick.-  mkTick' :: (CoreExpr -> CoreExpr) -- apply after adding tick (float through)-          -> (CoreExpr -> CoreExpr) -- apply before adding tick (float with)-          -> CoreExpr               -- current expression+  mkTick' :: (CoreExpr -> CoreExpr) -- Apply before adding tick (float with)+                                    -- Always a composition of (Tick t) wrappers+          -> CoreExpr               -- Current expression           -> CoreExpr-  mkTick' top rest expr = case expr of+          -- So in the call (mkTick' rest e), the expression+          --   (rest e)+          -- has the same type as e+          -- Returns an expression equivalent to (Tick t (rest e))+  mkTick' rest expr = case expr of     -- Float ticks into unsafe coerce the same way we would do with a cast.     Case scrut bndr ty alts@[Alt ac abs _rhs]       | Just rhs <- isUnsafeEqualityCase scrut bndr alts-      -> top $ mkTick' (\e -> Case scrut bndr ty [Alt ac abs e]) rest rhs+      -> Case scrut bndr ty [Alt ac abs (mkTick' rest rhs)]      -- Cost centre ticks should never be reordered relative to each     -- other. Therefore we can stop whenever two collide.     Tick t2 e-      | ProfNote{} <- t2, ProfNote{} <- t -> top $ Tick t $ rest expr+      | ProfNote{} <- t2, ProfNote{} <- t -> Tick t $ rest expr      -- Otherwise we assume that ticks of different placements float     -- through each other.-      | tickishPlace t2 /= tickishPlace t -> mkTick' (top . Tick t2) rest e+      | tickishPlace t2 /= tickishPlace t -> Tick t2 $ mkTick' rest e      -- For annotations this is where we make sure to not introduce     -- redundant ticks.-      | tickishContains t t2              -> mkTick' top rest e-      | tickishContains t2 t              -> orig_expr-      | otherwise                         -> mkTick' top (rest . Tick t2) e+      | tickishContains t t2              -> mkTick' rest e  -- Drop t2+      | tickishContains t2 t              -> rest e          -- Drop t+      | otherwise                         -> mkTick' (rest . Tick t2) e      -- Ticks don't care about types, so we just float all ticks     -- through them. Note that it's not enough to check for these@@ -344,14 +358,14 @@     -- expressions below ticks, such constructs can be the result of     -- unfoldings. We therefore make an effort to put everything into     -- the right place no matter what we start with.-    Cast e co   -> mkTick' (top . flip Cast co) rest e+    Cast e co   -> mkCast (mkTick' rest e) co     Coercion co -> Coercion co      Lam x e       -- Always float through type lambdas. Even for non-type lambdas,       -- floating is allowed for all but the most strict placement rule.       | not (isRuntimeVar x) || tickishPlace t /= PlaceRuntime-      -> mkTick' (top . Lam x) rest e+      -> Lam x $ mkTick' rest e        -- If it is both counting and scoped, we split the tick into its       -- two components, often allowing us to keep the counting tick on@@ -360,25 +374,27 @@       -- floated, and the lambda may then be in a position to be       -- beta-reduced.       | canSplit-      -> top $ Tick (mkNoScope t) $ rest $ Lam x $ mkTick (mkNoCount t) e+      -> Tick (mkNoScope t) $ rest $ Lam x $ mk_tick preserve_anf (mkNoCount t) e      App f arg       -- Always float through type applications.       | not (isRuntimeArg arg)-      -> mkTick' (top . flip App arg) rest f+      -> App (mkTick' rest f) arg        -- We can also float through constructor applications, placement       -- permitting. Again we can split.-      | isSaturatedConApp expr && (tickishPlace t==PlaceCostCentre || canSplit)+      | not preserve_anf -- this optimisation breaks ANF;+                         -- see Note [mkTick breaks ANF] in GHC.CoreToStg.Prep+      , isSaturatedConApp expr && (tickishPlace t==PlaceCostCentre || canSplit)       -> if tickishPlace t == PlaceCostCentre-         then top $ rest $ tickHNFArgs t expr-         else top $ Tick (mkNoScope t) $ rest $ tickHNFArgs (mkNoCount t) expr+         then rest $ tickHNFArgs t expr+         else Tick (mkNoScope t) $ rest $ tickHNFArgs (mkNoCount t) expr      Var x       | notFunction && tickishPlace t == PlaceCostCentre-      -> orig_expr+      -> rest expr  -- Drop t       | notFunction && canSplit-      -> top $ Tick (mkNoScope t) $ rest expr+      -> Tick (mkNoScope t) $ rest expr       where         -- SCCs can be eliminated on variables provided the variable         -- is not a function.  In these cases the SCC makes no difference:@@ -386,14 +402,20 @@         -- definition site.  When the variable refers to a function, however,         -- an SCC annotation on the variable affects the cost-centre stack         -- when the function is called, so we must retain those.-        notFunction = not (isFunTy (idType x))+        -- We must keep the tick around anything that might be a function,+        -- including:+        --+        --  1. Definite function types such as 'Int -> Bool'.+        --  2. Newtypes around function types, e.g. 'IO ()'. (#27225)+        --  3. Type family applications that reduce to (1) or (2).+        notFunction = not (mightBeFunTy (idType x))      Lit{}       | tickishPlace t == PlaceCostCentre-      -> orig_expr+      -> rest expr   -- Drop t      -- Catch-all: Annotate where we stand-    _any -> top $ Tick t $ rest expr+    _any -> Tick t $ rest expr  mkTicks :: [CoreTickish] -> CoreExpr -> CoreExpr mkTicks ticks expr = foldr mkTick expr ticks@@ -589,6 +611,28 @@ This makes it easy to find, though it makes matching marginally harder. -} +data BinderSwapDecision+  = NoBinderSwap+  | DoBinderSwap OutVar MCoercion++scrutOkForBinderSwap :: OutExpr -> BinderSwapDecision+-- If (scrutOkForBinderSwap e = DoBinderSwap v mco, then+--    e = v |> mco+-- See Note [Case of cast]+-- See Historical Note [Care with binder-swap on dictionaries]+--+-- We use this same function in SpecConstr, and Simplify.Iteration,+-- when something binder-swap-like is happening+--+-- See Note [Binder swap] in GHC.Core.Opt.OccurAnal+scrutOkForBinderSwap e+  = case e of+      Tick _ e        -> scrutOkForBinderSwap e  -- Drop ticks+      Var v           -> DoBinderSwap v MRefl+      Cast (Var v) co -> DoBinderSwap v (MCo co)+                         -- Cast: see Note [Case of cast]+      _               -> NoBinderSwap+ -- | Extract the default case alternative findDefault :: [Alt b] -> ([Alt b], Maybe (Expr b)) findDefault (Alt DEFAULT args rhs : alts) = assert (null args) (alts, Just rhs)@@ -650,11 +694,12 @@ -}  ----------------------------------mergeCaseAlts :: Id -> [CoreAlt] -> Maybe ([CoreBind], [CoreAlt])+mergeCaseAlts :: CoreExpr -> Id -> [CoreAlt] -> Maybe ([CoreBind], [CoreAlt]) -- See Note [Merge Nested Cases]-mergeCaseAlts outer_bndr (Alt DEFAULT _ deflt_rhs : outer_alts)+mergeCaseAlts scrut outer_bndr (Alt DEFAULT _ deflt_rhs : outer_alts)   | Just (joins, inner_alts) <- go deflt_rhs-  = Just (joins, mergeAlts outer_alts inner_alts)+  , Just aux_binds <- mk_aux_binds joins+  = Just ( aux_binds ++ joins, mergeAlts outer_alts inner_alts )                 -- NB: mergeAlts gives priority to the left                 --      case x of                 --        A -> e1@@ -664,6 +709,20 @@                 -- When we merge, we must ensure that e1 takes                 -- precedence over e2 as the value for A!   where+    scrut_fvs = exprFreeVars scrut++    -- See Note [Floating join points out of DEFAULT alternatives]+    mk_aux_binds join_binds+      | not (any mentions_outer_bndr join_binds)+      = Just []                         -- Good!  No auxiliary bindings needed+      | exprIsTrivial scrut+      , not (outer_bndr `elemVarSet` scrut_fvs)+      = Just [NonRec outer_bndr scrut]  -- Need a fixup binding+      | otherwise+      = Nothing                         -- Can't do it++    mentions_outer_bndr bind = outer_bndr `elemVarSet` bindFreeVars bind+     go :: CoreExpr -> Maybe ([CoreBind], [CoreAlt])      -- Whizzo: we can merge!@@ -701,24 +760,39 @@       = do { (joins, alts) <- go body               -- Check for capture; but only if we could otherwise do a merge-           ; let capture = outer_bndr `elem` bindersOf bind-                           || outer_bndr `elemVarSet` bindFreeVars bind-           ; guard (not capture)+             --    (i.e. the recursive `go` succeeds)+           ; guard (okToFloatJoin scrut_fvs outer_bndr bind) -           ; return (bind:joins, alts ) }+           ; return (bind : joins, alts ) }       | otherwise       = Nothing -    -- We don't want ticks to get in the way; just push them inwards.-    -- (This happens when you add SourceTicks e.g. GHC.Num.Integer.integerLt#)+    -- Push ticks **inwards** (when possible).+    -- See (MC5) in Note [Merge Nested Cases].     go (Tick t body)-      = do { (joins, alts) <- go body-           ; return (joins, [Alt con bs (Tick t rhs) | Alt con bs rhs <- alts]) }+      = do { (joins, alts) <- go body -- (MC4): any join points inside are floated out of the tick. +             -- Abort if this would put a non-soft-scope tick in between+             -- a join point binding and its jumps. See (MC6).+           ; guard $ null joins || t `tickishScopesLike` SoftScope+           ; return (joins, [Alt con bs (mkTick t rhs) | Alt con bs rhs <- alts])+           }+     go _ = Nothing -mergeCaseAlts _ _ = Nothing+mergeCaseAlts _ _ _ = Nothing +okToFloatJoin :: VarSet -> Id -> CoreBind -> Bool+-- Check a join-point binding to see if it can be floated out of+-- the DEFAULT branch of a `case`.+-- See Note [Floating join points out of DEFAULT alternatives]+okToFloatJoin scrut_fvs outer_bndr bind+  = not (any bad_bndr (bindersOf bind))+  where+    bad_bndr bndr = bndr == outer_bndr              -- (a)+                    || bndr `elemVarSet` scrut_fvs  -- (b)++ --------------------------------- mergeAlts :: [Alt a] -> [Alt a] -> [Alt a] -- ^ Merge alternatives preserving order; alternatives in@@ -802,8 +876,9 @@ refineDefaultAlt us mult tycon tys imposs_deflt_cons all_alts   | Alt DEFAULT _ rhs : rest_alts <- all_alts   , isAlgTyCon tycon            -- It's a data type, tuple, or unboxed tuples.-  , not (isNewTyCon tycon)      -- Exception 1 in Note [Refine DEFAULT case alternatives]-  , not (isTypeDataTyCon tycon) -- Exception 2 in Note [Refine DEFAULT case alternatives]+  , not (isNewTyCon tycon)        -- (DALT1) in Note [DataAlt restrictions] in GHC.Core+  , not (isTypeDataTyCon tycon)   -- (DALT2) in Note [DataAlt restrictions] in GHC.Core+  , not (isUnaryClassTyCon tycon) -- (DALT3) in Note [DataAlt restrictions] in GHC.Core   , Just all_cons <- tyConDataCons_maybe tycon   , let imposs_data_cons = mkUniqSet [con | DataAlt con <- imposs_deflt_cons]                              -- We now know it's a data type, so we can use@@ -924,13 +999,110 @@        So `mergeCaseAlts` floats out any join points. It doesn't float out       non-join-points unless the /outer/ case has just one alternative; doing-      so would risk more allocation+      so would risk more allocation. -(MC5) See Note [Cascading case merge]+      Floating out join points isn't entirely straightforward.+      See Note [Floating join points out of DEFAULT alternatives] +      Note also that `mergeCaseAlts` floats join points out of ticks, for which+      we need to be extra careful; see (MC6).++(MC5) We want to move ticks out of the way if possible, to prevent them from+      inhibiting optimisation. For example, say we have:++        case expensive of r {+          C1 -> rhs1; -- happy path+          _  -> scctick<doEdgeCase> (case r of { C2 -> rhs2; C3 -> rhs3 })+        }++      In this situation, we push the "doEdgeCase" tick **inwards** and proceed+      to merge cases, like so:++        case expensive of+          C1 -> rhs1+          C2 -> scctick<doEdgeCase> rhs2+          C3 -> scctick<doEdgeCase> rhs3++      This preserves the tick semantics, because this transformation:++        1. preserves counts,+        2. does not move cost in or out of the tick scope.++      (1) is clear: we will tick 'doEdgeCase' exactly in the C2/C3 alternatives,+      and we won't otherwise.+      For (2), recall that case is strict in Core. We already evaluated 'expensive',+      so re-scrutinising 'r' is free.++      This means that, perhaps surprisingly, this transformation is valid for+      **all** ticks, including non-floatable ones.++      In contrast, we would not want to move the tick outwards, because this:++        - will lead to additional counting of 'doEdgeCase' in the 'C1' (happy path) case,+        - risks attributing the cost of evaluating 'expensive' to 'doEdgeCase'.++(MC6) There is a dangerous interaction between (MC4) and (MC5), which can lead+      to invalid Core (as reported in #26642, #26929). Suppose we have:++        case f x of r ->+          scctick<foo>+            join j y = rhs in+            case r of { C1 -> j 1; C2 -> bar }++      If we naively carried out (MC4) and (MC5) together, this would result in:++        join j y = rhs in+          case f x of+            C1 -> scctick<foo> (j 1)+            C2 -> scctick<foo> bar++      This has moved the tick in between the join point binding 'j' and the+      join point jump, which is invalid. The simplifier cannot deal with such+      Core, resulting in #26642.++      The solution: abort whenever we would position a non-soft-scope tick+      inside a join point in this manner.+      An alternative would be to float the tick outwards, but as we saw in (MC5)+      this risks a grave misattribution of profiling costs, so we don't do that.++(MC7) See Note [Cascading case merge]+ See also Note [Example of case-merging and caseRules] in GHC.Core.Opt.Simplify.Utils +Note [Floating join points out of DEFAULT alternatives]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+Consider this, from (MC4) of Note [Merge Nested Cases]+   case x of r+     DEFAULT -> join j = rhs in case r of ...+     alts +We want to float that join point out to give this+   join j = rhs+   case x of r+     DEFAULT -> case r of ...+     alts++But doing so is flat-out wrong if the scoping gets messed up:+    (a) case x of r { DEFAULT -> join r = ... in ...r... }+    (b) case j of r { DEFAULT -> join j = ... in ... }+    (c) case x of r { DEFAULT -> join j = ...r.. in ... }+In all these cases we can't float the join point out because r changes its+meaning.  For (a) and (b) the Simplifier removes shadowing, so they'll+be solved in the next iteration.  But case (c) will persist.++Happily, we can fix up case (c) by adding an auxiliary binding, like this+    let r = e in+    join j = rhs[r]+    case e of r+       DEFAULT -> ...r...+       ...other alts...++We can only do this if+  * We don't introduce shadowing: that is `j` and `r` do not appear free in `e`.+    (Again the Simplifier will eliminate such shadowing.)+  * The scrutinee `e` is trivial so that the transformation doesn't duplicate work.++ Note [Cascading case merge] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Case merging should cascade in one sweep, because the Simplifier tries it /after/@@ -1046,38 +1218,9 @@    `imposs_deflt_cons` argument is populated with constructors which    are matched elsewhere. -There are two exceptions where we avoid refining a DEFAULT case:--* Exception 1: Newtypes--  We can have a newtype, if we are just doing an eval:--    case x of { DEFAULT -> e }--  And we don't want to fill in a default for them!--* Exception 2: `type data` declarations--  The data constructors for a `type data` declaration (see-  Note [Type data declarations] in GHC.Rename.Module) do not exist at the-  value level. Nevertheless, it is possible to strictly evaluate a value-  whose type is a `type data` declaration. Test case-  type-data/should_compile/T2294b.hs contains an example:--    type data T a where-      A :: T Int--    f :: T a -> ()-    f !x = ()--  We want to generate the following Core for f:--    f = \(@a) (x :: T a) ->-         case x of-           __DEFAULT -> ()--  Namely, we do _not_ want to match on `A`, as it doesn't exist at the value-  level! See wrinkle (W2b) in Note [Type data declarations] in GHC.Rename.Module+We must not refine the DEFAULT into a DataAlt for newtypes, `type data`+declarations, or unary classes, since none of these have a data constructor+that can appear in a DataAlt. See Note [DataAlt restrictions] in GHC.Core.   Note [Combine identical alternatives]@@ -1874,7 +2017,7 @@    | otherwise   = case idDetails fun of-      DFunId unary_class -> not unary_class+      DFunId terminating -> terminating          -- DFuns terminate, unless the dict is implemented          -- by a no-op in which case they may not          -- See (UCM3) in Note [Unary class magic] in GHC.Core.TyCon@@ -2856,7 +2999,7 @@     Str=<1L><ML>,     Unf=OtherCon []] =         {} \r [x y]-            case x<TagProper> of x' [Occ=Once1] {+            case x<TagVal[TagEPT]> of x' [Occ=Once1] {               __DEFAULT ->                   case y of y' [Occ=Once1] {                   __DEFAULT ->@@ -2881,8 +3024,8 @@     Str=<1L><!L>,     Unf=OtherCon []] =         {} \r [x y]-            case y<TagProper> of y' [Occ=Once1] { __DEFAULT ->-            case x<TagProper> of x' [Occ=Once1] {+            case y<TagVal[TagEPT]> of y' [Occ=Once1] { __DEFAULT ->+            case x<TagVal[TagEPT]> of x' [Occ=Once1] {               __DEFAULT ->                   case Find.$wmyPred y' of pred_y [Occ=Once1] {                   __DEFAULT ->
GHC/CoreToStg/Prep.hs view
@@ -787,7 +787,9 @@        ; return (FloatTick tickish `consFloat` floats, body) }   | otherwise   = do { body <- cpeBodyNF env expr-       ; return (emptyFloats, mkTick tickish' body) }+       ; return (emptyFloats, mkTickCpe tickish' body) }+    -- Use mkTickCpe and not mkTick, as the latter may break ANF (#27182).+    -- See (TickANF2) in Note [mkTick breaks ANF].   where     tickish' | Breakpoint ext bid fvs <- tickish              -- See also 'substTickish'@@ -891,6 +893,28 @@             ; rhs' <- cpeBodyNF env2 rhs             ; return (Alt con bs' rhs') } +{- Note [mkTick breaks ANF]+~~~~~~~~~~~~~~~~~~~~~~~~~~~+mkTick does not preserve the ANF property as required by Core Prep (see+Note [CorePrep invariants]), as seen in #27182. Given:++  mkTick scc<foo> (\ (eta :: Char -> Bool) -> BindP (p :: Int) eta)++mkTick will push the SCC into the constructor application, resulting in:++  \ (eta :: Char -> Bool) -> BindP (p :: Int) (scc<oneM> eta)++To avoid this problem (at least until 'mkTick' is more thoroughly reworked to+avoid this infelicity, see #27141), we define a variant of 'mkTick', called+'mkTickCpe', which does not push ticks into constructor applications (this is+the only optimisation done by 'mkTick' that can break ANF).++We prefer using a small variant of 'mkTick' rather than using the 'Tick'+constructor, as the latter can slightly degrade profiling reports by failing to+combine ticks (can result in spurious cost centres with 0 entries appearing in+profiling reports).+-}+ -- --------------------------------------------------------------------------- --              CpeBody: produces a result satisfying CpeBody -- ---------------------------------------------------------------------------@@ -928,7 +952,9 @@ rhsToBody env (Tick t expr)   | tickishScoped t == NoScope  -- only float out of non-scoped annotations   = do { (floats, expr') <- rhsToBody env expr-       ; return (floats, mkTick t expr') }+       ; return (floats, mkTickCpe t expr') }+    -- Use mkTickCpe and not mkTick, as the latter may break ANF (#27182).+    -- See Note [mkTick breaks ANF].  rhsToBody env (Cast e co)         -- You can get things like@@ -1075,6 +1101,9 @@        || f `hasKey` nospecIdKey        -- Replace (nospec a) with a             -- See Note [nospecId magic] in GHC.Types.Id.Make +        -- NB: keep this in sync with GHC.HsToCore.Pmc.Solver.Types.coreExprAsPmLit,+        -- as that also needs to see through these magic Ids.+         -- Consider the code:         --         --      lazy (f x) y@@ -1226,7 +1255,7 @@     rebuild_app' env (a : as) fun' floats ss rt_ticks req_depth = case a of       -- See Note [Ticks and mandatory eta expansion]       _ | not (null rt_ticks), req_depth <= 0-        -> let tick_fun = foldr mkTick fun' rt_ticks+        -> let tick_fun = foldr mkTickCpe fun' rt_ticks            in rebuild_app' env (a : as) tick_fun floats ss rt_ticks req_depth        AIApp (Type arg_ty)@@ -1874,74 +1903,132 @@ most code paths anyway, we get to turn the unknown eval in the callee into a known call at the call site. -Very Nasty Wrinkle+(SEV1) There is a very nasty wrinkle: we must be very careful not to speculate+       recursive calls!  Doing so might well change termination behavior. -We must be very careful not to speculate recursive calls!  Doing so-might well change termination behavior.+       That comes up in practice for DFuns, which are considered ok-for-spec,+       because they always immediately return a constructor.+       See Note [NON-BOTTOM-DICTS invariant] in GHC.Core. -That comes up in practice for DFuns, which are considered ok-for-spec,-because they always immediately return a constructor.-See Note [NON-BOTTOM-DICTS invariant] in GHC.Core.+       But not so if you speculate the recursive call, as #20836 shows: -But not so if you speculate the recursive call, as #20836 shows:+         class Foo m => Foo m where+           runFoo :: m a -> m a+         newtype Trans m a = Trans { runTrans :: m a }+         instance Monad m => Foo (Trans m) where+           runFoo = id -  class Foo m => Foo m where-    runFoo :: m a -> m a-  newtype Trans m a = Trans { runTrans :: m a }-  instance Monad m => Foo (Trans m) where-    runFoo = id+       (NB: class Foo m => Foo m` looks weird and needs -XUndecidableSuperClasses. The+       example in #20836 is more compelling, but boils down to the same thing.)+       This program compiles to the following DFun for the `Trans` instance: -(NB: class Foo m => Foo m` looks weird and needs -XUndecidableSuperClasses. The-example in #20836 is more compelling, but boils down to the same thing.)-This program compiles to the following DFun for the `Trans` instance:+         Rec {+         $fFooTrans+           = \ @m $dMonad -> C:Foo ($fFooTrans $dMonad) (\ @a -> id)+         end Rec } -  Rec {-  $fFooTrans-    = \ @m $dMonad -> C:Foo ($fFooTrans $dMonad) (\ @a -> id)-  end Rec }+       Note that the DFun immediately terminates and produces a dictionary, just+       like DFuns ought to, but it calls itself recursively to produce the `Foo m`+       dictionary. But alas, if we treat `$fFooTrans` as always-terminating, so+       that we can speculate its calls, and hence use call-by-value, we get: -Note that the DFun immediately terminates and produces a dictionary, just-like DFuns ought to, but it calls itself recursively to produce the `Foo m`-dictionary. But alas, if we treat `$fFooTrans` as always-terminating, so-that we can speculate its calls, and hence use call-by-value, we get:+         $fFooTrans+           = \ @m $dMonad -> case ($fFooTrans $dMonad) of sc ->+                             C:Foo sc (\ @a -> id) -  $fFooTrans-    = \ @m $dMonad -> case ($fFooTrans $dMonad) of sc ->-                      C:Foo sc (\ @a -> id)+       and that's an infinite loop!+       Note that this bad-ness only happens in `$fFooTrans`'s own RHS. In the+       *body* of the letrec, it's absolutely fine to use call-by-value on+       `foo ($fFooTrans d)`. -and that's an infinite loop!-Note that this bad-ness only happens in `$fFooTrans`'s own RHS. In the-*body* of the letrec, it's absolutely fine to use call-by-value on-`foo ($fFooTrans d)`.+       Our solution is this: we track in cpe_rec_ids the set of enclosing+       recursively-bound Ids, the RHSs of which we are currently transforming and then+       in 'exprOkForSpecEval' (a special entry point to 'exprOkForSpeculation',+       basically) we'll say that any binder in this set is not ok-for-spec. -Our solution is this: we track in cpe_rec_ids the set of enclosing-recursively-bound Ids, the RHSs of which we are currently transforming and then-in 'exprOkForSpecEval' (a special entry point to 'exprOkForSpeculation',-basically) we'll say that any binder in this set is not ok-for-spec.+       Note if we have a letrec group `Rec { f1 = rhs1; ...; fn = rhsn }`, and we+       prep up `rhs1`, we have to include not only `f1`, but all binders of the group+       `f1..fn` in this set, otherwise our fix is not robust wrt. mutual recursive+       DFuns. -Note if we have a letrec group `Rec { f1 = rhs1; ...; fn = rhsn }`, and we-prep up `rhs1`, we have to include not only `f1`, but all binders of the group-`f1..fn` in this set, otherwise our fix is not robust wrt. mutual recursive-DFuns.+       NB: If at some point we decide to have a termination analysis for general+       functions (#8655, !1866), we need to take similar precautions for (guarded)+       recursive functions: -NB: If at some point we decide to have a termination analysis for general-functions (#8655, !1866), we need to take similar precautions for (guarded)-recursive functions:+         repeat x = x : repeat x -  repeat x = x : repeat x+       Same problem here: As written, repeat evaluates rapidly to WHNF. So `repeat x`+       is a cheap call that we are willing to speculate, but *not* in repeat's RHS.+       Fortunately, pce_rec_ids already has all the information we need in that case. -Same problem here: As written, repeat evaluates rapidly to WHNF. So `repeat x`-is a cheap call that we are willing to speculate, but *not* in repeat's RHS.-Fortunately, pce_rec_ids already has all the information we need in that case.+       The problem is very similar to Note [Eta reduction in recursive RHSs].+       Here as well as there it is *unsound* to change the termination properties+       of the very function whose termination properties we are exploiting. -The problem is very similar to Note [Eta reduction in recursive RHSs].-Here as well as there it is *unsound* to change the termination properties-of the very function whose termination properties we are exploiting.+       It is also similar to Note [Do not strictify a DFun's parameter dictionaries],+       where marking recursive DFuns (of undecidable *instances*) strict in dictionary+       *parameters* leads to quite the same change in termination as above. -It is also similar to Note [Do not strictify a DFun's parameter dictionaries],-where marking recursive DFuns (of undecidable *instances*) strict in dictionary-*parameters* leads to quite the same change in termination as above.+(SEV2) The situation in (SEV1) can cross modules.  `cpe_rec_ids` is module-local,+       so it does not catch a recursion that goes through an hs-boot import.+       Suppose Mid and Callee form a module loop, and Mid sees Callee through its+       hs-boot file: +         -- Mid.hs+         $fCAT = \ @a $dCB -> C:CA ($fxCBT $dCB) ...+         -- Callee.hs+         $fCBT = \ @a $dCB -> C:CB ($fCAT  $dCB) ...++       Neither module can see that these two call each other, so each looks+       non-recursive, and we speculate the inner call in both:++         $fCAT = \ @a $dCB -> case $fxCBT $dCB of s { __DEFAULT -> C:CA s ... }+         $fCBT = \ @a $dCB -> case $fCAT  $dCB of s { __DEFAULT -> C:CB s ... }++       Now each forces the other and the program loops. Such a cycle must cross an+       hs-boot edge, so we do not speculate a call whose callee has a BootUnfolding.+       Note [Inlining and hs-boot files] in GHC.CoreToIface does the same for+       infinite inlining.++(SEV3) Belt and braces: do not speculate absent bindings.++       In 'decideFloatInfo' we decline to speculate a binding whose demand is+       absent.  There is no point in speculating an absent binding, since its+       value is (presumably) not needed.++       This used to matter more. Worker/wrapper would bind an absent dictionary+       to a rubbish literal filler, and speculation could force a superclass+       selection out of that rubbish literal, causing a segfault (#25924).+       Nowadays we never make a filler for a dictionary in the first place, so+       this can no longer happen and the guard is merely belt and braces.+       See Note [Don't make fillers for constraint types]+       in GHC.Core.Opt.WorkWrap.Utils.++Note [Controlling Speculative Evaluation]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~++Most of the time, speculative evaluation in the coreprep phase has a positive+effect on performance, however we have found that some forms of speculative+evaluation can lead to large performance regressions. See #25284.++Therefore we have some flags to control which types of speculative evaluation+are done:++  -fspec-eval+     Globally enable/disable speculative evaluation ( -fno-spec-eval also turns+     off all other speculative evaluation). On by default for all+     optimization levels. Turning on this flag by itself should never cause+     a performance regression. Please open a ticket if you find any.++  -fspec-eval-dictfun+     Enable speculative evaluation for dictionary functions. Off by default+     since it can cause an increase in allocations (#24284). We have no+     examples that show a large performance improvement when turning on this+     flag. Please open a ticket if you find any.++Also see the optimization section in the User's Guide for the description of+these flags and when to use them.+ Note [BindInfo and FloatInfo] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The `BindInfo` of a `Float` describes whether it will be case-bound or@@ -1998,31 +2085,6 @@ See also Note [Floats and FloatDecision] for how we maintain whole groups of floats and how far they go. -Note [Controlling Speculative Evaluation]-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~--Most of the time, speculative evaluation in the coreprep phase has a positive-effect on performance, however we have found that some forms of speculative-evaluation can lead to large performance regressions. See #25284.--Therefore we have some flags to control which types of speculative evaluation-are done:--  -fspec-eval-     Globally enable/disable speculative evaluation ( -fno-spec-eval also turns-     off all other speculative evaluation). On by default for all-     optimization levels. Turning on this flag by itself should never cause-     a performance regression. Please open a ticket if you find any.--  -fspec-eval-dictfun-     Enable speculative evaluation for dictionary functions. Off by default-     since it can cause an increase in allocations (#24284). We have no-     examples that show a large performance improvement when turning on this-     flag. Please open a ticket if you find any.--Also see the optimization section in the User's Guide for the description of-these flags and when to use them.- Note [Floats and FloatDecision] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We have a special datatype `Floats` for modelling a telescope of `FloatingBind`@@ -2201,12 +2263,16 @@   | is_string             = (CaseBound, TopLvlFloatable)       -- String literals are unboxed (so must be case-bound) and float to       -- the top-level-  | ok_for_spec           = (CaseBound, case lev of Unlifted -> LazyContextFloatable+  | ok_for_spec+  , not (isAbsDmd dmd)    = (CaseBound, case lev of Unlifted -> LazyContextFloatable                                                     Lifted   -> TopLvlFloatable)-      -- See Note [Speculative evaluation]+      -- See Note [Speculative evaluation], and (SEV3) for isAbsDmd       -- Ok-for-spec-eval things will be case-bound, lifted or not.       -- But when it's lifted we are ok with floating it to top-level       -- (where it is actually bound lazily).+      --+      -- Don't speculate an absent binding. See #25924 and+      -- "Belt and braces" in Note [Speculative evaluation].   | Unlifted <- lev       = (CaseBound, StrictContextFloatable)   | isStrUsedDmd dmd      = (CaseBound, StrictContextFloatable)       -- These will never be floated out of a lazy RHS context@@ -2252,11 +2318,18 @@     ok_for_spec = exprOkForSpecEval call_ok_for_spec rhs     -- See Note [Controlling Speculative Evaluation]     call_ok_for_spec x-      | is_rec_call x                           = False-      | not (cp_specEval cfg)                   = False-      | not (cp_specEvalDFun cfg) && isDFunId x = False+      -- See Note [Speculative evaluation]+      | is_rec_call x                           = False  -- See (SEV1)+      | is_boot_call x                          = False  -- See (SEV2)++      -- See [Controlling speculative evaluation]+      | not (cp_specEval cfg)                   = False  -- Flag -fspec-eval+      | not (cp_specEvalDFun cfg) && isDFunId x = False  -- Flag -fspec-eval-dictfun+       | otherwise                               = True-    is_rec_call = (`elemUnVarSet` cpe_rec_ids env)+    is_rec_call  = (`elemUnVarSet` cpe_rec_ids env)+    is_boot_call = isBootUnfolding . realIdUnfolding+      -- See Note [Speculative evaluation], Very Nasty Wrinkle      -- See Note [Pin evaluatedness on floats]     bndr' | is_hnf    = bndr `setIdUnfolding` evaldUnfolding@@ -2279,7 +2352,7 @@     mk_bind (UnsafeEqualityCase scrut b con bs) body       = mkSingleAltCase scrut b con bs body     mk_bind (FloatTick tickish) body-      = mkTick tickish body+      = mkTickCpe tickish body  -- | Put floats at top-level deFloatTop :: Floats -> [CoreBind]@@ -2713,7 +2786,7 @@ wrapTicks :: Floats -> CoreExpr -> (Floats, CoreExpr) wrapTicks floats expr   | (floats1, ticks1) <- fold_fun go floats-  = (floats1, foldrOL mkTick expr ticks1)+  = (floats1, foldrOL mkTickCpe expr ticks1)   where fold_fun f floats =            let (binds, ticks) = foldlOL f (nilOL,nilOL) (fs_binds floats)            in (floats { fs_binds = binds }, ticks)@@ -2733,8 +2806,8 @@          wrap t (Float bind bound info) = Float (wrapBind t bind) bound info         wrap _ f                 = pprPanic "Unexpected FloatingBind" (ppr f)-        wrapBind t (NonRec binder rhs) = NonRec binder (mkTick t rhs)-        wrapBind t (Rec pairs)         = Rec (mapSnd (mkTick t) pairs)+        wrapBind t (NonRec binder rhs) = NonRec binder (mkTickCpe t rhs)+        wrapBind t (Rec pairs)         = Rec (mapSnd (mkTickCpe t) pairs)  ------------------------------------------------------------------------------ -- Numeric literals
GHC/Data/OsPath.hs view
@@ -11,6 +11,16 @@   -- * Common utility functions   , (</>)   , (<.>)+  , splitSearchPath+  , isRelative+  , normalise+  , dropTrailingPathSeparator+  , takeDirectory+  , isSuffixOf+  , doesDirectoryExist+  , doesFileExist+  , getDirectoryContents+  , createDirectoryIfMissing   )   where @@ -20,6 +30,8 @@ import GHC.Utils.Panic (panic)  import System.OsPath+import System.OsString (isSuffixOf)+import System.Directory.OsPath (doesDirectoryExist, doesFileExist, getDirectoryContents, createDirectoryIfMissing) import System.Directory.Internal (os)  -- | Decode an 'OsPath' to 'FilePath', throwing an 'error' if decoding failed.
GHC/Driver/Backpack.hs view
@@ -93,6 +93,7 @@ import qualified GHC.Unit.Home.Graph as HUG import GHC.Unit.Home.ModInfo import GHC.Unit.Home.PackageTable+import GHC.Unit.External.Index (cacheExternalUnitDatabase)  -- | Entry point to compile a Backpack file. doBackpack :: [FilePath] -> Ghc ()@@ -172,6 +173,8 @@                -> BkpM a withBkpSession cid insts deps session_type do_this = do     dflags <- getDynFlags+    env <- getSession+    unitIndex <- liftIO $ hscUnitIndex env     let cid_fs = unitFS cid         is_primary = False         uid_str = unpackFS (mkInstantiatedUnitHash cid insts)@@ -191,8 +194,8 @@                  | otherwise = sub_comp (key_base p)          mk_temp_env hsc_env =-          hscUpdateFlags (\dflags -> mk_temp_dflags (hsc_units hsc_env) dflags) hsc_env-        mk_temp_dflags unit_state dflags = dflags+          hscUpdateFlags (\dflags -> mk_temp_dflags unitIndex (hsc_units hsc_env) dflags) hsc_env+        mk_temp_dflags unit_index unit_state dflags = dflags             { backend = case session_type of                             TcSession -> noBackend                             _         -> backend dflags@@ -239,8 +242,7 @@             , importPaths = []             -- Synthesize the flags             , packageFlags = packageFlags dflags ++ map (\(uid0, rn) ->-              let uid = unwireUnit unit_state-                        $ improveUnit unit_state+              let uid = unwireUnit unit_index                         $ renameHoleUnit unit_state (listToUFM insts) uid0               in ExposePackage                 (showSDoc dflags@@ -309,19 +311,16 @@     -- The compilation dependencies are just the appropriately filled     -- in unit IDs which must be compiled before we can compile.     let hsubst = listToUFM insts-        deps0 = map (renameHoleUnit (hsc_units hsc_env) hsubst) raw_deps+        deps = map (renameHoleUnit (hsc_units hsc_env) hsubst) raw_deps      -- Build dependencies OR make sure they make sense. BUT NOTE,     -- we can only check the ones that are fully filled; the rest     -- we have to defer until we've typechecked our local signature.     -- TODO: work this into GHC.Driver.Make!!-    forM_ (zip [1..] deps0) $ \(i, dep) ->+    forM_ (zip [1..] deps) $ \(i, dep) ->         case session of             TcSession -> return ()-            _ -> compileInclude (length deps0) (i, dep)--    -- IMPROVE IT-    let deps = map (improveUnit (hsc_units hsc_env)) deps0+            _ -> compileInclude (length deps) (i, dep)      mb_old_eps <- case session of                     TcSession -> fmap Just getEpsGhc@@ -350,9 +349,9 @@               | otherwise               = [Nothing]         linkables <- liftIO $ catMaybes <$> concatHpt takeLinkables (hsc_HPT hsc_env)+        unit_index <- liftIO $ hscUnitIndex hsc_env         let             obj_files = concatMap linkableFiles linkables-            state     = hsc_units hsc_env              compat_fs = unitIdFS cid             compat_pn = PackageName compat_fs@@ -378,7 +377,7 @@                         -- really used for anything, so we leave it                         -- blank for now.                         TcSession -> []-                        _ -> map (toUnitId . unwireUnit state)+                        _ -> map (toUnitId . unwireUnit unit_index)                                 $ deps ++ [ moduleUnit mod                                           | (_, mod) <- insts                                           , not (isHoleModule mod) ],@@ -427,6 +426,26 @@         ok <- load' noIfaceCache LoadAllTargets mkUnknownDiagnostic (Just msg) mod_graph         when (failed ok) (liftIO $ exitWith (ExitFailure 1)) +-- | Adds an in-memory database for the given 'UnitInfo'.+--+-- As this in-memory database can't be read from disk, we immediately cache it in the+-- 'ExternalUnitDatabaseCache'+addInMemoryDatabase :: GhcMonad m => DynFlags -> UnitInfo -> m DynFlags+addInMemoryDatabase dflags u = do+    hsc_env <- getSession+    let newdb = UnitDatabase+          { unitDatabasePath  = unsafeEncodeUtf $ "(in memory " ++ showSDoc dflags (ppr (unitId u)) ++ ")"+          , unitDatabaseUnits = [u]+          }+    let uic = hscUIC hsc_env+    liftIO $ cacheExternalUnitDatabase uic newdb+    -- Ordering matters here! We prepend the new unit database, because 'packageDBFlags'+    -- works like a stack, where what's on top takes precedence over what's below (same as right-to-left when given at the CLI).+    -- The new db needs highest precedence to overwrite any other in-memory units that potentially occur in the dbs below it.+    pure dflags+          { packageDBFlags = PackageDB (PkgDbPath (unitDatabasePath newdb)) : packageDBFlags dflags+          }+ -- | Register a new virtual unit database containing a single unit addUnit :: GhcMonad m => UnitInfo -> m () addUnit u = do@@ -434,18 +453,14 @@     logger <- getLogger     let dflags0 = hsc_dflags hsc_env     let old_unit_env = hsc_unit_env hsc_env-    newdbs <- case ue_unit_dbs old_unit_env of-        Nothing  -> panic "addUnit: called too early"-        Just dbs ->-         let newdb = UnitDatabase-               { unitDatabasePath  = "(in memory " ++ showSDoc dflags0 (ppr (unitId u)) ++ ")"-               , unitDatabaseUnits = [u]-               }-         in return (dbs ++ [newdb]) -- added at the end because ordering matters-    (dbs,unit_state,home_unit,mconstants) <- liftIO $ initUnits logger dflags0 (Just newdbs) (hsc_all_home_unit_ids hsc_env) +    dflags1 <- addInMemoryDatabase dflags0 u++    (unit_state,home_unit,mconstants) <- liftIO $ initUnits logger dflags1 (ue_uic old_unit_env) (hsc_all_home_unit_ids hsc_env)++     -- update platform constants-    dflags <- liftIO $ updatePlatformConstants dflags0 mconstants+    dflags <- liftIO $ updatePlatformConstants dflags1 mconstants      let unit_env = UnitEnv           { ue_platform  = targetPlatform dflags@@ -455,9 +470,10 @@           , ue_home_unit_graph =                 HUG.unitEnv_singleton                     (homeUnitId home_unit)-                    (HUG.mkHomeUnitEnv unit_state (Just dbs) dflags (ue_hpt old_unit_env) (Just home_unit))+                    (HUG.mkHomeUnitEnv unit_state dflags (ue_hpt old_unit_env) (Just home_unit))           , ue_eps       = ue_eps old_unit_env           , ue_module_graph = ue_module_graph old_unit_env+          , ue_uic = ue_uic old_unit_env           }     setSession $ hscSetFlags dflags $ hsc_env { hsc_unit_env = unit_env } @@ -786,8 +802,8 @@      env <- getBkpEnv     src_hash <- liftIO $ getFileHash (bkp_filename env)-    hi_timestamp <- liftIO $ modificationTimeIfExists (ml_hi_file location)-    hie_timestamp <- liftIO $ modificationTimeIfExists (ml_hie_file location)+    hi_timestamp <- liftIO $ modificationTimeIfExists (ml_hi_file_ospath location)+    hie_timestamp <- liftIO $ modificationTimeIfExists (ml_hie_file_ospath location)     let loc = srcLocSpan (mkSrcLoc (mkFastString (bkp_filename env)) 1 1)      let fc = hsc_FC hsc_env@@ -872,8 +888,8 @@                                 HsSrcFile  -> os "hs")                              hsc_src     -- This duplicates a pile of logic in GHC.Driver.Make-    hi_timestamp <- liftIO $ modificationTimeIfExists (ml_hi_file location)-    hie_timestamp <- liftIO $ modificationTimeIfExists (ml_hie_file location)+    hi_timestamp <- liftIO $ modificationTimeIfExists (ml_hi_file_ospath location)+    hie_timestamp <- liftIO $ modificationTimeIfExists (ml_hie_file_ospath location)      -- Also copied from 'getImports'     let (src_idecls, ord_idecls) = partition ((== IsBoot) . ideclSource . unLoc) imps
GHC/Driver/CodeOutput.hs view
@@ -37,7 +37,7 @@ import GHC.Driver.Ppr import GHC.Driver.Backend -import GHC.Data.OsPath+import GHC.Data.OsPath qualified as OsPath import qualified GHC.Data.ShortText as ST import GHC.Data.Stream           ( liftIO ) import qualified GHC.Data.Stream as Stream@@ -60,8 +60,6 @@ import GHC.Types.ForeignStubs import GHC.Types.Unique.DSM -import System.Directory-import System.FilePath import System.IO import Data.Set (Set) import qualified Data.Set as Set@@ -124,6 +122,7 @@                   { a <- linted_cmm_stream                   ; let stubs = genForeignStubs a                   ; emitInitializerDecls this_mod stubs+                  ; emitFinalizerDecls this_mod stubs                   ; return (stubs, a) }          ; let dus1 = newTagDUniqSupply 'n' dus0@@ -138,19 +137,23 @@         }  -- | See Note [Initializers and finalizers in Cmm] in GHC.Cmm.InitFini for details.-emitInitializerDecls :: Module -> ForeignStubs -> CgStream RawCmmGroup ()-emitInitializerDecls this_mod (ForeignStubs _ cstub)-  | initializers <- getInitializers cstub-  , not $ null initializers =-      let init_array = CmmData sect statics-          lbl = mkInitializerArrayLabel this_mod-          sect = Section InitArray lbl+emitInitializerDecls, emitFinalizerDecls :: Module -> ForeignStubs -> CgStream RawCmmGroup ()+emitInitializerDecls = emitInitFiniArrayDecls InitArray mkInitializerArrayLabel getInitializers+emitFinalizerDecls   = emitInitFiniArrayDecls FiniArray mkFinalizerArrayLabel   getFinalizers++emitInitFiniArrayDecls :: SectionType -> (Module -> CLabel) -> (CStub -> [CLabel])+                       -> Module -> ForeignStubs -> CgStream RawCmmGroup ()+emitInitFiniArrayDecls sect_type mk_lbl get_labels this_mod (ForeignStubs _ cstub)+  | labels <- get_labels cstub+  , not $ null labels =+      let lbl     = mk_lbl this_mod+          sect    = Section sect_type lbl           statics = CmmStaticsRaw lbl             [ CmmStaticLit $ CmmLabel fn_name-            | fn_name <- initializers+            | fn_name <- labels             ]-    in Stream.yield [init_array]-emitInitializerDecls _ _ = return ()+    in Stream.yield [CmmData sect statics]+emitInitFiniArrayDecls _ _ _ _ _ = return ()  doOutput :: String -> (Handle -> IO a) -> IO a doOutput filenm io_action = bracket (openFile filenm WriteMode) hClose io_action@@ -323,10 +326,9 @@         stub_h_file_exists <-           case mkStubPaths (initFinderOpts dflags) (moduleName mod) location of             Nothing -> pure False-            Just path -> do-              let stub_h = unsafeDecodeUtf path-              createDirectoryIfMissing True (takeDirectory stub_h)-              outputForeignStubs_help stub_h stub_h_output_w+            Just stub_h -> do+              OsPath.createDirectoryIfMissing True (OsPath.takeDirectory stub_h)+              outputForeignStubs_help (OsPath.unsafeDecodeUtf stub_h) stub_h_output_w                     ("#include <HsFFI.h>\n" ++ cplusplus_hdr) cplusplus_ftr          putDumpFileMaybe logger Opt_D_dump_foreign
GHC/Driver/Config/CmmToLlvm.hs view
@@ -23,7 +23,6 @@     , llvmCgContext              = initSDocContext dflags PprCode     , llvmCgFillUndefWithGarbage = gopt Opt_LlvmFillUndefWithGarbage dflags     , llvmCgSplitSection         = gopt Opt_SplitSections dflags-    , llvmCgAvxEnabled           = isAvxEnabled dflags     , llvmCgBmiVersion           = case platformArch (targetPlatform dflags) of                                       ArchX86_64 -> bmiVersion dflags                                       ArchX86    -> bmiVersion dflags
GHC/Driver/Config/Core/Lint.hs view
@@ -20,7 +20,7 @@ import GHC.Core.Lint.Interactive import GHC.Core.Opt.Pipeline.Types import GHC.Core.Opt.Simplify ( SimplifyOpts(..) )-import GHC.Core.Opt.Simplify.Env ( SimplMode(..) )+import GHC.Core.Opt.Simplify.Env ( SimplMode(..), SimplPhase(..) ) import GHC.Core.Opt.Monad import GHC.Core.Coercion @@ -114,9 +114,9 @@ showLintWarnings :: CoreToDo -> Bool -- Disable Lint warnings on the first simplifier pass, because -- there may be some INLINE knots still tied, which is tiresomely noisy-showLintWarnings (CoreDoSimplify cfg) = case sm_phase (so_mode cfg) of-  InitialPhase -> False-  _ -> True+showLintWarnings (CoreDoSimplify cfg)+  | SimplPhase InitialPhase <- sm_phase (so_mode cfg)+  = False showLintWarnings _ = True  perPassFlags :: DynFlags -> CoreToDo -> LintFlags
GHC/Driver/Config/Core/Opt/Simplify.hs view
@@ -10,7 +10,7 @@ import GHC.Core.Rules ( RuleBase ) import GHC.Core.Opt.Pipeline.Types ( CoreToDo(..) ) import GHC.Core.Opt.Simplify ( SimplifyExprOpts(..), SimplifyOpts(..) )-import GHC.Core.Opt.Simplify.Env ( FloatEnable(..), SimplMode(..) )+import GHC.Core.Opt.Simplify.Env ( FloatEnable(..), SimplMode(..), SimplPhase(..) ) import GHC.Core.Opt.Simplify.Monad ( TopEnvConfig(..) )  import GHC.Driver.Config ( initOptCoercionOpts )@@ -59,7 +59,7 @@ initSimplMode :: DynFlags -> CompilerPhase -> String -> SimplMode initSimplMode dflags phase name = SimplMode   { sm_names = [name]-  , sm_phase = phase+  , sm_phase = SimplPhase phase   , sm_rules = gopt Opt_EnableRewriteRules dflags   , sm_eta_expand = gopt Opt_DoLambdaEtaExpansion dflags   , sm_cast_swizzle = True
GHC/Driver/Config/Finder.hs view
@@ -9,7 +9,7 @@ import GHC.Unit.Finder.Types import GHC.Data.FastString import GHC.Data.OsPath-import qualified Data.Map as Map+import GHC.Types.Unique.Map  -- | Create a new 'FinderOpts' from DynFlags. initFinderOpts :: DynFlags -> FinderOpts@@ -22,7 +22,7 @@   , finder_workingDirectory = fmap unsafeEncodeUtf $ workingDirectory flags   , finder_thisPackageName  = mkFastString <$> thisPackageName flags   , finder_hiddenModules = hiddenModules flags-  , finder_reexportedModules = Map.fromList [(known_as, is_as) | ReexportedModule is_as known_as <- reverse (reexportedModules flags)]+  , finder_reexportedModules = listToUniqMap [(known_as, is_as) | ReexportedModule is_as known_as <- reverse (reexportedModules flags)]   , finder_hieDir = fmap unsafeEncodeUtf $ hieDir flags   , finder_hieSuf = unsafeEncodeUtf $ hieSuf flags   , finder_hiDir = fmap unsafeEncodeUtf $ hiDir flags
GHC/Driver/Config/StgToCmm.hs view
@@ -88,7 +88,7 @@   , stgToCmmAvx           = isAvxEnabled                   dflags   , stgToCmmAvx2          = isAvx2Enabled                  dflags   , stgToCmmAvx512f       = isAvx512fEnabled               dflags-  , stgToCmmTickyAP       = gopt Opt_Ticky_AP dflags+  , stgToCmmUseStdApThunk = not $ gopt Opt_Ticky_AP dflags   -- See Note [Saving foreign call target to local]   , stgToCmmSaveFCallTargetToLocal = any (callerSaves platform) $ activeStgRegs platform   } where profile  = targetProfile dflags
GHC/Driver/Downsweep.hs view
@@ -1264,7 +1264,7 @@   | ms_hs_hash old_summary == src_hash &&       not (gopt Opt_ForceRecomp (hsc_dflags hsc_env)) = do            -- update the object-file timestamp-           obj_timestamp <- modificationTimeIfExists (ml_obj_file location)+           obj_timestamp <- modificationTimeIfExists (ml_obj_file_ospath location)             -- We have to repopulate the Finder's cache for file targets            -- because the file might not even be on the regular search path@@ -1276,8 +1276,8 @@                hsc_src = ms_hsc_src old_summary            addModuleToFinder fc mod location hsc_src -           hi_timestamp <- modificationTimeIfExists (ml_hi_file location)-           hie_timestamp <- modificationTimeIfExists (ml_hie_file location)+           hi_timestamp <- modificationTimeIfExists (ml_hi_file_ospath location)+           hie_timestamp <- modificationTimeIfExists (ml_hie_file_ospath location)             return $ Right              ( old_summary@@ -1481,10 +1481,10 @@ makeNewModSummary :: HscEnv -> MakeNewModSummary -> IO ModSummary makeNewModSummary hsc_env MakeNewModSummary{..} = do   let PreprocessedImports{..} = nms_preimps-  obj_timestamp <- modificationTimeIfExists (ml_obj_file nms_location)-  dyn_obj_timestamp <- modificationTimeIfExists (ml_dyn_obj_file nms_location)-  hi_timestamp <- modificationTimeIfExists (ml_hi_file nms_location)-  hie_timestamp <- modificationTimeIfExists (ml_hie_file nms_location)+  obj_timestamp <- modificationTimeIfExists (ml_obj_file_ospath nms_location)+  dyn_obj_timestamp <- modificationTimeIfExists (ml_dyn_obj_file_ospath nms_location)+  hi_timestamp <- modificationTimeIfExists (ml_hi_file_ospath nms_location)+  hie_timestamp <- modificationTimeIfExists (ml_hie_file_ospath nms_location)    extra_sig_imports <- findExtraSigImports hsc_env nms_hsc_src pi_mod_name   (implicit_sigs, _inst_deps) <- implicitRequirementsShallow (hscSetActiveUnitId (moduleUnitId nms_mod) hsc_env) pi_theimps
GHC/Driver/DynFlags.hs view
@@ -35,6 +35,7 @@         packageFlagsChanged,         IgnorePackageFlag(..), TrustFlag(..),         PackageDBFlag(..), PkgDbRef(..),+        isPackageDbRef,         Option(..), showOpt,         DynLibLoader(..),         positionIndependent,@@ -101,6 +102,7 @@ import GHC.Data.Bool import GHC.Data.EnumSet (EnumSet) import GHC.Data.Maybe+import GHC.Data.OsPath ( OsPath ) import GHC.Builtin.Names ( mAIN_NAME ) import GHC.Driver.Backend import GHC.Driver.Flags@@ -143,6 +145,7 @@ import GHC.Foreign (withCString, peekCString)  import qualified Data.Set as Set+import GHC.Types.Unique.Set  import qualified GHC.LanguageExtensions as LangExt @@ -261,7 +264,7 @@   -- Note [Filepaths and Multiple Home Units]   workingDirectory      :: Maybe FilePath,   thisPackageName       :: Maybe String, -- ^ What the package is called, use with multiple home units-  hiddenModules         :: Set.Set ModuleName,+  hiddenModules         :: !(UniqSet ModuleName),   reexportedModules     :: [ReexportedModule],    -- ways@@ -522,6 +525,7 @@                          `catchIOError` \_ -> return False  ghcNoUnicodeEnv <- lookupEnv "GHC_NO_UNICODE"  let useUnicode' = isNothing ghcNoUnicodeEnv && canUseUnicode+ canUseColor <- stderrSupportsAnsiColors  maybeGhcColorsEnv  <- lookupEnv "GHC_COLORS"  maybeGhcColoursEnv <- lookupEnv "GHC_COLOURS"  let adjustCols (Just env) = Col.parseScheme env@@ -533,9 +537,9 @@  return dflags{         useUnicode    = useUnicode',         useColor      = useColor',-        canUseColor   = stderrSupportsAnsiColors,+        canUseColor   = canUseColor,         -- if the terminal supports color, we assume it supports links as well-        canUseErrorLinks = stderrSupportsAnsiColors,+        canUseErrorLinks = canUseColor,         colScheme     = colScheme',         tmpDir        = TempDir tmp_dir         }@@ -597,7 +601,7 @@          workingDirectory        = Nothing,         thisPackageName         = Nothing,-        hiddenModules           = Set.empty,+        hiddenModules           = emptyUniqSet,         reexportedModules       = [],          objectDir               = Nothing,@@ -815,7 +819,7 @@ data PackageArg =       PackageArg String    -- ^ @-package@, by 'PackageName'     | UnitIdArg Unit       -- ^ @-package-id@, by 'Unit'-  deriving (Eq, Show)+  deriving (Eq, Ord, Show)  instance Outputable PackageArg where     ppr (PackageArg pn) = text "package" <+> text pn@@ -836,7 +840,7 @@     modRenamingWithImplicit :: Bool, -- ^ Bring all exposed modules into scope?     modRenamings :: [(ModuleName, ModuleName)] -- ^ Bring module @m@ into scope                                                --   under name @n@.-  } deriving (Eq)+  } deriving (Eq, Ord) instance Outputable ModRenaming where     ppr (ModRenaming b rns) = ppr b <+> parens (ppr rns) @@ -854,15 +858,22 @@ data PackageFlag   = ExposePackage   String PackageArg ModRenaming -- ^ @-package@, @-package-id@   | HidePackage     String -- ^ @-hide-package@-  deriving (Eq) -- NB: equality instance is used by packageFlagsChanged+  deriving (Eq, Ord) -- NB: equality instance is used by packageFlagsChanged  data PackageDBFlag   = PackageDB PkgDbRef   | NoUserPackageDB   | NoGlobalPackageDB   | ClearPackageDBs-  deriving (Eq)+  deriving (Eq, Ord) +isPackageDbRef :: PackageDBFlag -> Maybe PkgDbRef+isPackageDbRef = \ case+  PackageDB ref -> Just ref+  NoUserPackageDB -> Nothing+  NoGlobalPackageDB -> Nothing+  ClearPackageDBs -> Nothing+ packageFlagsChanged :: DynFlags -> DynFlags -> Bool packageFlagsChanged idflags1 idflags0 =   packageFlags idflags1 /= packageFlags idflags0 ||@@ -935,8 +946,8 @@ data PkgDbRef   = GlobalPkgDb   | UserPkgDb-  | PkgDbPath FilePath-  deriving Eq+  | PkgDbPath OsPath+  deriving (Eq, Ord)   @@ -1160,7 +1171,6 @@       Opt_SpecialiseIncoherents,       Opt_WriteSelfRecompInfo     ]-     ++ [f | (ns,f) <- optLevelFlags, 0 `elem` ns]              -- The default -O0 options 
GHC/Driver/Env.hs view
@@ -13,6 +13,7 @@    , hsc_HUE    , hsc_HUG    , hsc_all_home_unit_ids+   , hscUnitIndex    , hscUpdateLoggerFlags    , hscUpdateHUG    , hscInsertHPT@@ -24,6 +25,8 @@    , mkInteractiveHscEnv    , runInteractiveHsc    , hscEPS+   , hscEUD+   , hscUIC    , hscInterp    , prepareAnnotations    , discardIC@@ -55,6 +58,8 @@ import GHC.Runtime.Interpreter.Types (Interp)  import GHC.Unit+import GHC.Unit.External.Database+import GHC.Unit.External.Index import GHC.Unit.Module.ModGuts import GHC.Unit.Module.ModIface import GHC.Unit.Module.ModDetails@@ -221,6 +226,15 @@ hscEPS :: HscEnv -> IO ExternalPackageState hscEPS hsc_env = readIORef (euc_eps (ue_eps (hsc_unit_env hsc_env))) +hscEUD :: HscEnv -> IO (ExternalUnitDatabases UnitId)+hscEUD = readExternalUnitDatabases . hscUIC++hscUnitIndex :: HscEnv -> IO UnitIndex+hscUnitIndex hsc_env = ueUI (hsc_unit_env hsc_env)++hscUIC :: HscEnv -> UnitIndexCache+hscUIC hsc_env = ue_uic (hsc_unit_env hsc_env)+ -------------------------------------------------------------------------------- -- * Queries on Transitive Closure --------------------------------------------------------------------------------@@ -247,13 +261,13 @@ -- | Find instances visible from the given set of imports hugInstancesBelow :: HscEnv -> UnitId -> ModuleNameWithIsBoot -> IO (InstEnv, [FamInst]) hugInstancesBelow hsc_env uid mnwib = do- let mn = gwib_mod mnwib+ let mn = mkModule uid (gwib_mod mnwib)  (insts, famInsts) <-      unzip . concat <$>        hugSomeThingsBelowUs (\mod_info ->                                   let details = hm_details mod_info                                   -- Don't include instances for the current module-                                  in if moduleName (mi_module (hm_iface mod_info)) == mn+                                  in if fmap toUnitId (mi_module (hm_iface mod_info)) == mn                                        then []                                        else [(md_insts details, md_fam_insts details)])                           True -- Include -hi-boot
GHC/Driver/Errors.hs view
@@ -7,27 +7,59 @@  import GHC.Driver.Errors.Types import GHC.Prelude+import GHC.Types.SrcLoc import GHC.Types.SourceError import GHC.Types.Error+import GHC.Utils.Json import GHC.Utils.Error-import GHC.Utils.Outputable (hang, ppr, ($$),  text, mkErrStyle, sdocStyle, updSDocContext )+import GHC.Utils.Outputable import GHC.Utils.Logger  printMessages :: forall a. (Diagnostic a) => Logger -> DiagnosticOpts a -> DiagOpts -> Messages a -> IO ()-printMessages logger msg_opts opts msgs-  = sequence_ [ let style = mkErrStyle name_ppr_ctx-                    ctx   = (diag_ppr_ctx opts) { sdocStyle = style }-                in (if log_diags_as_json-                    then logJsonMsg logger (MCDiagnostic sev reason (diagnosticCode dia)) msg-                    else logMsg logger (MCDiagnostic sev reason (diagnosticCode dia)) s $-                  updSDocContext (\_ -> ctx) (messageWithHints dia))-              | msg@MsgEnvelope { errMsgSpan       = s,-                                  errMsgDiagnostic = dia,-                                  errMsgSeverity   = sev,-                                  errMsgReason     = reason,-                                  errMsgContext    = name_ppr_ctx }-                  <- sortMsgBag (Just opts) (getMessages msgs) ]+printMessages logger msg_opts opts = mapM_ (printMessage logger msg_opts opts) . sortMessages   where+    sortMessages :: Messages a -> [MsgEnvelope a]+    sortMessages = sortMsgBag (Just opts) . getMessages++printMessage :: forall a. (Diagnostic a) => Logger -> DiagnosticOpts a -> DiagOpts -> MsgEnvelope a -> IO ()+printMessage logger msg_opts opts message+  | log_diags_as_json = do+      decorated <- decorateDiagnostic logflags messageClass location doc+      let+        rendered :: String+        rendered = renderWithContext (log_default_user_context logflags) decorated++        jsonMessage :: JsonDoc+        jsonMessage = jsonDiagnostic rendered message++      logJsonMsg logger messageClass jsonMessage++  | otherwise = logMsg logger messageClass location doc+  where+    logflags :: LogFlags+    logflags = logFlags logger++    doc :: SDoc+    doc = updSDocContext (\_ -> ctx) (messageWithHints diagnostic)++    messageClass :: MessageClass+    messageClass = MCDiagnostic severity (errMsgReason message) (diagnosticCode diagnostic)++    style :: PprStyle+    style = mkErrStyle (errMsgContext message)++    location :: SrcSpan+    location = errMsgSpan message++    ctx :: SDocContext+    ctx = (diag_ppr_ctx opts) { sdocStyle = style }++    diagnostic :: a+    diagnostic = errMsgDiagnostic message++    severity :: Severity+    severity = errMsgSeverity message+     messageWithHints :: a -> SDoc     messageWithHints e =       let main_msg = formatBulleted $ diagnosticMessage msg_opts e@@ -36,6 +68,8 @@                [h] -> main_msg $$ hang (text "Suggested fix:") 2 (ppr h)                hs  -> main_msg $$ hang (text "Suggested fixes:") 2                                        (formatBulleted  $ mkDecorated . map ppr $ hs)++    log_diags_as_json :: Bool     log_diags_as_json = log_diagnostics_as_json (logFlags logger)  -- | Given a bag of diagnostics, turn them into an exception if
GHC/Driver/Errors/Ppr.hs view
@@ -28,6 +28,8 @@ import GHC.Types.SrcLoc import Data.Version +import System.Semaphore+  ( SemaphoreError(..), getSemaphoreProtocolVersion ) import Language.Haskell.Syntax.Decls (RuleDecl(..)) import GHC.Tc.Errors.Types (TcRnMessage) import GHC.HsToCore.Errors.Types (DsMessage)@@ -94,6 +96,20 @@ instance HasDefaultDiagnosticOpts DriverMessageOpts where   defaultOpts = DriverMessageOpts (defaultDiagnosticOpts @PsMessage) (defaultDiagnosticOpts @IfaceMessage) +pprSemaphoreError :: SemaphoreError -> SDoc+pprSemaphoreError = \case+  SemaphoreAlreadyExists nm ->+    text "a semaphore named" <+> quotes (text nm) <+> text "already exists"+  SemaphoreDoesNotExist nm ->+    text "no semaphore named" <+> quotes (text nm)+  SemaphoreIncompatibleVersion got want ->+    text "protocol version mismatch (got v"+    <> int (getSemaphoreProtocolVersion got)+    <> text ", supported v"+    <> int (getSemaphoreProtocolVersion want) <> text ")"+  SemaphoreOtherError ioe ->+    text (show ioe)+ instance Diagnostic DriverMessage where   type DiagnosticOpts DriverMessage = DriverMessageOpts   diagnosticMessage opts = \case@@ -282,6 +298,10 @@             ++ " and "             ++ llvmVersionStr supportedLlvmVersionUpperBound             ++ ") and reinstall GHC to ensure -fllvm works")+    DriverSemaphoreOpenFailure _ err+      -> mkSimpleDecorated $+        text "Failed to open -jsem semaphore:" <+> pprSemaphoreError err <>+        text "; ignoring -jsem and compiling sequentially."    diagnosticReason = \case     DriverUnknownMessage m@@ -353,6 +373,8 @@       -> ErrorWithoutFlag     DriverNoConfiguredLLVMToolchain       -> WarningWithoutFlag+    DriverSemaphoreOpenFailure {}+      -> WarningWithFlag Opt_WarnSemaphoreOpenFailure    diagnosticHints = \case     DriverUnknownMessage m@@ -425,6 +447,20 @@     DriverInstantiationNodeInDependencyGeneration {}       -> noHints     DriverNoConfiguredLLVMToolchain+      -> noHints+    DriverSemaphoreOpenFailure buildingCabal (SemaphoreIncompatibleVersion received supported)+      | received < supported+      -> let required = getSemaphoreProtocolVersion supported+             target = case buildingCabal of+               YesBuildingCabalPackage -> UpgradeCabalInstall+               NoBuildingCabalPackage  -> UpgradeJobserver+         in [SuggestUpgradeForSemaphoreVersionMismatch target required]+      | received > supported+      -> [SuggestUpgradeForSemaphoreVersionMismatch+            UpgradeGHC (getSemaphoreProtocolVersion received)]+      | otherwise+      -> noHints+    DriverSemaphoreOpenFailure {}       -> noHints    diagnosticCode = constructorCode @GHC
GHC/Driver/Errors/Types.hs view
@@ -41,6 +41,7 @@  import GHC.Generics ( Generic ) +import System.Semaphore ( SemaphoreError ) import GHC.Tc.Errors.Types import GHC.Iface.Errors.Types @@ -411,6 +412,18 @@    -}   DriverNoConfiguredLLVMToolchain :: DriverMessage++  {-| DriverSemaphoreOpenFailure is a warning that occurs when GHC fails to+      open the semaphore specified by @-jsem@, e.g. the socket does not+      exist, the protocol version is incompatible, or a system error+      occurred.  GHC ignores @-jsem@ and compiles sequentially.++      The 'BuildingCabalPackage' flag controls whether the diagnostic+      hint suggests upgrading @cabal-install@ (it only does so when GHC+      is invoked by Cabal).+  -}+  DriverSemaphoreOpenFailure :: !BuildingCabalPackage -> !SemaphoreError -> DriverMessage+  deriving instance Generic DriverMessage 
GHC/Driver/Flags.hs view
@@ -378,6 +378,7 @@                 ,(Opt_ByteCodeAndObjectCode, turnOn, Opt_WriteIfSimplifiedCore)                 ,(Opt_InfoTableMap, turnOn, Opt_InfoTableMapWithStack)                 ,(Opt_InfoTableMap, turnOn, Opt_InfoTableMapWithFallback)+                ,(Opt_InfoTableMap, turnOn, Opt_Ticky_AP)                 ] ++ validHoleFitsImpliedGFlags  -- | General flags that are switched on/off when other general flags are switched@@ -760,6 +761,8 @@     -- | Instruct GHCi to load all targets on startup    | Opt_GhciDoLoadTargets+   -- | Instruct GHCi to import all loaded targets on startup+   | Opt_GhciImportLoadedTargets     | Opt_HelpfulErrors    | Opt_DeferTypeErrors             -- Since 7.6@@ -1107,6 +1110,7 @@        -- See Note [Quantifying over equalities in RULES] in GHC.Tc.Gen.Sig    | Opt_WarnUnusableUnpackPragmas                   -- Since 9.14    | Opt_WarnPatternNamespaceSpecifier               -- Since 9.14+   | Opt_WarnSemaphoreOpenFailure    deriving (Eq, Ord, Show, Enum, Bounded)  -- | Return the names of a WarningFlag@@ -1228,6 +1232,7 @@   Opt_WarnRuleLhsEqualities                       -> "rule-lhs-equalities" :| []   Opt_WarnUnusableUnpackPragmas                   -> "unusable-unpack-pragmas" :| []   Opt_WarnPatternNamespaceSpecifier               -> "pattern-namespace-specifier" :| []+  Opt_WarnSemaphoreOpenFailure                    -> "semaphore-open-failure" :| []  -- ----------------------------------------------------------------------------- -- Standard sets of warning options@@ -1373,7 +1378,8 @@         Opt_WarnUselessSpecialisations,         Opt_WarnDeprecatedPragmas,         Opt_WarnRuleLhsEqualities,-        Opt_WarnUnusableUnpackPragmas+        Opt_WarnUnusableUnpackPragmas,+        Opt_WarnSemaphoreOpenFailure       ]  -- | Things you get with @-W@.
GHC/Driver/Main.hs view
@@ -319,7 +319,7 @@   where     home_unit_graph hpt = HUG.unitEnv_singleton                         (homeUnitId_ dflags)-                        (HUG.mkHomeUnitEnv emptyUnitState Nothing dflags hpt Nothing)+                        (HUG.mkHomeUnitEnv emptyUnitState dflags hpt Nothing)  newHscEnvWithHUG :: FilePath -> DynFlags -> UnitId -> HomeUnitGraph -> IO HscEnv newHscEnvWithHUG top_dir top_dynflags cur_unit home_unit_graph = do@@ -693,7 +693,7 @@                     Nothing -> hscParse' mod_summary             tc_result0 <- tcRnModule' mod_summary keep_rn' hpm             if hsc_src == HsigFile-                then do (iface, _) <- liftIO $ hscSimpleIface hsc_env Nothing tc_result0 mod_summary+                then do (iface, _) <- liftIO $ hscSimpleIface hsc_env Nothing Nothing tc_result0 mod_summary                         ioMsgMaybe $ hoistTcRnMessage $                             tcRnMergeSignatures hsc_env hpm tc_result0 iface                 else return tc_result0@@ -871,7 +871,7 @@                -- we will decide if we need them or not.                bc_linkable <- checkByteCode checked_iface mod_summary (homeMod_bytecode old_linkable)                obj_linkable <- liftIO $ checkObjects lcl_dflags (homeMod_object old_linkable) mod_summary-               trace_if (hsc_logger hsc_env) (vcat [text "BCO linkable", nest 2 (ppr bc_linkable), text "Object Linkable", ppr obj_linkable])+               trace_if (hsc_logger hsc_env) (vcat [text "BCO linkable", nest 2 (ppr bc_linkable), text "Object Linkable", nest 2 (ppr obj_linkable)])                 let just_bc = justBytecode <$> bc_linkable                    just_o  = justObjects  <$> obj_linkable@@ -1018,12 +1018,13 @@ -- | Assemble 'WholeCoreBindings' if the interface contains Core bindings. iface_core_bindings :: ModIface -> ModLocation -> Maybe WholeCoreBindings iface_core_bindings iface wcb_mod_location =-  mi_simplified_core <&> \(IfaceSimplifiedCore bindings foreign') ->+  mi_simplified_core <&> \(IfaceSimplifiedCore bindings wcb_modBreaks foreign') ->     WholeCoreBindings {       wcb_bindings = bindings,       wcb_module = mi_module,       wcb_mod_location,-      wcb_foreign = foreign'+      wcb_foreign = foreign',+      wcb_modBreaks     }   where     ModIface {mi_module, mi_simplified_core} = iface@@ -1054,7 +1055,7 @@       linkable $ BCOs bcos :| [DotO fo ForeignObject | fo <- fos]      linkable parts = do-      if_time <- modificationTimeIfExists (ml_hi_file location)+      if_time <- modificationTimeIfExists (ml_hi_file_ospath location)       time <- maybe getCurrentTime pure if_time       return $! Linkable time (mi_module iface) parts @@ -1075,7 +1076,7 @@       linkable $ NE.singleton (LazyBCOs bcos fos)      linkable parts = do-      if_time <- modificationTimeIfExists (ml_hi_file location)+      if_time <- modificationTimeIfExists (ml_hi_file_ospath location)       time <- maybe getCurrentTime pure if_time       return $!Linkable time (mi_module iface) parts @@ -1161,11 +1162,11 @@     gen_bytecode core_binds stubs foreign_files = do       let cgi_guts = CgInteractiveGuts wcb_module core_binds                       (typeEnvTyCons type_env) stubs foreign_files-                      Nothing []+                      wcb_modBreaks []       trace_if logger (text "Generating ByteCode for" <+> ppr wcb_module)       generateByteCode hsc_env cgi_guts wcb_mod_location -    WholeCoreBindings {wcb_module, wcb_mod_location, wcb_foreign} = wcb+    WholeCoreBindings {wcb_module, wcb_mod_location, wcb_foreign, wcb_modBreaks} = wcb      logger = hsc_logger hsc_env @@ -1292,7 +1293,8 @@               liftIO $ hscTidy hsc_env simplified_guts            (iface, _details) <- liftIO $-            hscSimpleIface hsc_env (Just $ cg_binds cg_guts) tc_result summary+            hscSimpleIface hsc_env (Just $ cg_binds cg_guts)+             (cg_modBreaks cg_guts) tc_result summary            liftIO $ hscMaybeWriteIface logger dflags True iface mb_old_hash (ms_location summary) @@ -1307,7 +1309,7 @@       -- and generate a simple interface.       _ -> do         (iface, _details) <- liftIO $-          hscSimpleIface hsc_env Nothing tc_result summary+          hscSimpleIface hsc_env Nothing Nothing tc_result summary          liftIO $ hscMaybeWriteIface logger dflags True iface mb_old_hash (ms_location summary) @@ -1757,7 +1759,7 @@             Sf_Safe | not trust_own_pkg         -> True             Sf_SafeInferred | not trust_own_pkg -> True             _ | isHomeModule home_unit mod      -> True-            _ -> unitIsTrusted $ unsafeLookupUnit unit_state (moduleUnit m)+            _ -> isUnitTrusted unit_state (moduleUnit m)      lookup' :: Module -> Hsc (Maybe ModIface)     lookup' m = do@@ -1778,7 +1780,7 @@     let errors = S.foldr go emptyBag pkgs         state  = hsc_units hsc_env         go pkg acc-            | unitIsTrusted $ unsafeLookupUnitId state pkg+            | isUnitIdTrusted state pkg             = acc             | otherwise             = (`consBag` acc)@@ -1886,17 +1888,19 @@ -- generates interface files. See Note [simpleTidyPgm - mkBootModDetailsTc] hscSimpleIface :: HscEnv                -> Maybe CoreProgram+               -> Maybe ModBreaks                -> TcGblEnv                -> ModSummary                -> IO (ModIface, ModDetails)-hscSimpleIface hsc_env mb_core_program tc_result summary-    = runHsc hsc_env $ hscSimpleIface' mb_core_program tc_result summary+hscSimpleIface hsc_env mb_core_program mb_modBreaks tc_result summary+    = runHsc hsc_env $ hscSimpleIface' mb_core_program mb_modBreaks tc_result summary  hscSimpleIface' :: Maybe CoreProgram+                -> Maybe ModBreaks                 -> TcGblEnv                 -> ModSummary                 -> Hsc (ModIface, ModDetails)-hscSimpleIface' mb_core_program tc_result summary = do+hscSimpleIface' mb_core_program mb_modBreaks tc_result summary = do     hsc_env   <- getHscEnv     logger    <- getLogger     details   <- liftIO $ mkBootModDetailsTc logger tc_result@@ -1904,7 +1908,7 @@     new_iface         <- {-# SCC "MkFinalIface" #-}            liftIO $-               mkIfaceTc hsc_env safe_mode details summary mb_core_program tc_result+               mkIfaceTc hsc_env safe_mode details summary mb_core_program mb_modBreaks tc_result     -- And the answer is ...     liftIO $ dumpIfaceStats hsc_env     return (new_iface, details)@@ -2782,7 +2786,7 @@    case interp of     -- always generate JS code for the JS interpreter (no bytecode!)-    Interp (ExternalInterp (ExtJS i)) _ _ ->+    Interp { interpInstance = ExternalInterp (ExtJS i) } ->       jsCodeGen hsc_env srcspan i this_mod stg_binds_with_deps binding_id      _ -> do
GHC/Driver/Make.hs view
@@ -109,13 +109,14 @@  import qualified Data.Map as Map import qualified Data.Set as Set+import GHC.Types.Unique.Set  import Control.Concurrent.MVar import Control.Monad import qualified Control.Monad.Catch as MC import Data.IORef import Data.Maybe-import Data.List (sortOn, groupBy, sortBy)+import Data.List (sort, sortOn, groupBy, sortBy) import qualified Data.List as List import System.FilePath @@ -313,14 +314,15 @@   where     diag_opts = initDiagOpts dflags -    unit_mods = Set.fromList (map ms_mod_name+    unit_mods :: UniqSet ModuleName+    unit_mods = mkUniqSet (map ms_mod_name                   (filter (\ms -> ms_unitid ms == homeUnitId_ dflags)                        (mgModSummaries mod_graph)))      reexported_mods = reexportedModules dflags     hidden_mods     = hiddenModules dflags -    hidden_warns = hidden_mods `Set.difference` unit_mods+    hidden_warns = hidden_mods `minusUniqSet` unit_mods      lookupModule mn = findImportedModule hsc_env mn NoPkgQual @@ -337,7 +339,7 @@     final_msgs hidden_warns reexported_warns           =         unionManyMessages $-          [warn (DriverUnknownHiddenModules (homeUnitId_ dflags) (Set.toList hidden_warns)) | not (Set.null hidden_warns)]+          [warn (DriverUnknownHiddenModules (homeUnitId_ dflags) (sort $ nonDetEltsUniqSet hidden_warns)) | not (isEmptyUniqSet hidden_warns)]           ++ [warn (DriverUnknownReexportedModules (homeUnitId_ dflags) reexported_warns) | not (null reexported_warns)]  -- | Describes which modules of the module graph need to be loaded.
GHC/Driver/MakeAction.hs view
@@ -28,16 +28,39 @@ import GHC.Driver.Messager import GHC.Driver.MakeSem +#if defined(wasm32_HOST_ARCH) || defined(javascript_HOST_ARCH)+import System.Semaphore+  ( SemaphoreIdentifier )+#else+import System.Semaphore+  ( SemaphoreError, SemaphoreIdentifier )+#endif++#if !(defined(wasm32_HOST_ARCH) || defined(javascript_HOST_ARCH))+import GHC.Driver.Config.Diagnostic ( initDiagOpts, initPrintConfig )+import GHC.Driver.Errors ( printOrThrowDiagnostics )+import GHC.Types.Error ( singleMessage )+import GHC.Types.SrcLoc ( noSrcSpan )+import GHC.Utils.Error ( mkPlainMsgEnvelope )+#endif import GHC.Utils.Logger import GHC.Utils.TmpFs +#if defined(wasm32_HOST_ARCH) || defined(javascript_HOST_ARCH)+import Control.Concurrent ( ThreadId, killThread, forkIOWithUnmask )+#else import Control.Concurrent ( newQSem, waitQSem, signalQSem, ThreadId, killThread, forkIOWithUnmask )+#endif import qualified GHC.Conc as CC import Control.Concurrent.MVar import Control.Monad import qualified Control.Monad.Catch as MC +#if defined(wasm32_HOST_ARCH) || defined(javascript_HOST_ARCH)+import GHC.Conc ( getNumProcessors )+#else import GHC.Conc ( getNumProcessors, getNumCapabilities, setNumCapabilities )+#endif import Control.Monad.Trans.Reader import GHC.Driver.Pipeline.LogQueue import Control.Concurrent.STM@@ -49,7 +72,7 @@ mkWorkerLimit dflags =   case parMakeCount dflags of     Nothing -> pure $ num_procs 1-    Just (ParMakeSemaphore h) -> pure (JSemLimit (SemaphoreName h))+    Just (ParMakeSemaphore h) -> pure (JSemLimit h)     Just ParMakeNumProcessors -> num_procs <$> getNumProcessors     Just (ParMakeThisMany n) -> pure $ num_procs n   where@@ -65,8 +88,8 @@ data WorkerLimit   = NumProcessorsLimit Int   | JSemLimit-    SemaphoreName-      -- ^ Semaphore name to use+    SemaphoreIdentifier+      -- ^ Semaphore identifier from @-jsem@   deriving Eq  -- | Environment used when compiling a module@@ -106,6 +129,7 @@                     }   in runAllPipelines (NumProcessorsLimit 1) env all_pipelines +#if !(defined(wasm32_HOST_ARCH) || defined(javascript_HOST_ARCH)) runNjobsAbstractSem :: Int -> (AbstractSem -> IO a) -> IO a runNjobsAbstractSem n_jobs action = do   compile_sem <- newQSem n_jobs@@ -122,17 +146,26 @@     resetNumCapabilities = set_num_caps n_capabilities   MC.bracket_ updNumCapabilities resetNumCapabilities $ action asem -runWorkerLimit :: WorkerLimit -> (AbstractSem -> IO a) -> IO a-#if defined(wasm32_HOST_ARCH)-runWorkerLimit _ action = do+#endif++runWorkerLimit :: Logger -> DynFlags -> WorkerLimit -> (AbstractSem -> IO a) -> IO a+#if defined(wasm32_HOST_ARCH) || defined(javascript_HOST_ARCH)+runWorkerLimit _logger _dflags _ action = do   lock <- newMVar ()   action $ AbstractSem (takeMVar lock) (putMVar lock ()) #else-runWorkerLimit worker_limit action = case worker_limit of+runWorkerLimit logger dflags worker_limit action = case worker_limit of     NumProcessorsLimit n_jobs ->       runNjobsAbstractSem n_jobs action-    JSemLimit sem ->-      runJSemAbstractSem sem action+    JSemLimit sem_ident -> do+      result <- MC.try @_ @SemaphoreError $ runJSemAbstractSem sem_ident action+      case result of+        Right a -> return a+        Left err -> do+          let diag = DriverSemaphoreOpenFailure (checkBuildingCabalPackage dflags) err+              msg  = singleMessage $ mkPlainMsgEnvelope (initDiagOpts dflags) noSrcSpan diag+          printOrThrowDiagnostics logger (initPrintConfig dflags) (initDiagOpts dflags) (GhcDriverMessage <$> msg)+          runNjobsAbstractSem 1 action #endif  -- | Build and run a pipeline@@ -159,7 +192,7 @@   thread_safe_logger <- liftIO $ makeThreadSafe (hsc_logger plugin_hsc_env)   let thread_safe_hsc_env = plugin_hsc_env { hsc_logger = thread_safe_logger } -  runWorkerLimit worker_limit $ \abstract_sem -> do+  runWorkerLimit (hsc_logger plugin_hsc_env) (hsc_dflags plugin_hsc_env) worker_limit $ \abstract_sem -> do     let env = MakeEnv { hsc_env = thread_safe_hsc_env                       , withLogger = withParLog log_queue_queue_var                       , compile_sem = abstract_sem
GHC/Driver/MakeSem.hs view
@@ -1,26 +1,33 @@ {-# LANGUAGE BlockArguments #-}-{-# LANGUAGE NamedFieldPuns #-}+{-# LANGUAGE CPP #-} {-# LANGUAGE RecordWildCards #-}-{-# LANGUAGE TupleSections #-}-{-# LANGUAGE NumericUnderscores #-}  -- | Implementation of a jobserver using system semaphores. -- -- module GHC.Driver.MakeSem-  ( -- * JSem: parallelism semaphore backed+  (+#if !(defined(wasm32_HOST_ARCH) || defined(javascript_HOST_ARCH))+    -- * JSem: parallelism semaphore backed     -- by a system semaphore (Posix/Windows)-    runJSemAbstractSem--  -- * System semaphores-  , Semaphore, SemaphoreName(..)+    runJSemAbstractSem,+#endif    -- * Abstract semaphores-  , AbstractSem(..)+    AbstractSem(..)   , withAbstractSem   )   where +#if defined(wasm32_HOST_ARCH) || defined(javascript_HOST_ARCH)++import System.Semaphore+  ( AbstractSem(..)+  , withAbstractSem+  )++#else+ import GHC.Prelude import GHC.Conc import GHC.Data.OrdList@@ -30,6 +37,15 @@ import GHC.Utils.Json  import System.Semaphore+  ( AbstractSem(..)+  , ClientSemaphore+  , SemaphoreIdentifier+  , SemaphoreToken+  , openSemaphore+  , releaseSemaphoreToken+  , waitOnSemaphore+  , withAbstractSem+  )  import Control.Monad import qualified Control.Monad.Catch as MC@@ -49,11 +65,14 @@ -- available from the semaphore. data Jobserver   = Jobserver-  { jSemaphore :: !Semaphore+  { jSemaphore :: !ClientSemaphore     -- ^ The semaphore which controls available resources   , jobs :: !(TVar JobResources)     -- ^ The currently pending jobs, and the resources     -- obtained from the semaphore+  , activeChild :: !(TVar (Maybe (ThreadId, TMVar (Maybe MC.SomeException))))+    -- ^ Handle on the current acquire thread (if any). The loop's exit+    -- handler reads this to drain a still-running child on shutdown.   }  data JobserverOptions@@ -84,6 +103,9 @@   , jobsWaiting :: !(OrdList (TMVar ()))     -- ^ Pending jobs waiting on a token, the job will be blocked on the TMVar so putting into     -- the TMVar will allow the job to continue.+  , heldTokens  :: [SemaphoreToken]+    -- ^ Actual semaphore tokens (for release/cleanup).+    -- Length should equal tokensOwned - 1 (the implicit token has no SemaphoreToken).   }  instance Outputable JobResources where@@ -96,9 +118,9 @@           ] )  -- | Add one new token.-addToken :: JobResources -> JobResources-addToken jobs@( Jobs { tokensOwned = owned, tokensFree = free })-  = jobs { tokensOwned = owned + 1, tokensFree = free + 1 }+addToken :: SemaphoreToken -> JobResources -> JobResources+addToken tok jobs@( Jobs { tokensOwned = owned, tokensFree = free, heldTokens = toks })+  = jobs { tokensOwned = owned + 1, tokensFree = free + 1, heldTokens = tok : toks }  -- | Free one token. addFreeToken :: JobResources -> JobResources@@ -114,12 +136,14 @@       (text "removeFreeToken:" <+> ppr free)   $ jobs { tokensFree = free - 1 } --- | Return one owned token.-removeOwnedToken :: JobResources -> JobResources-removeOwnedToken jobs@( Jobs { tokensOwned = owned })+-- | Return one owned token, extracting the 'SemaphoreToken' for release.+removeOwnedToken :: JobResources -> (SemaphoreToken, JobResources)+removeOwnedToken jobs@( Jobs { tokensOwned = owned, heldTokens = toks })   = assertPpr (owned > 1)       (text "removeOwnedToken:" <+> ppr owned)-  $ jobs { tokensOwned = owned - 1 }+  $ case toks of+      (t:rest) -> (t, jobs { tokensOwned = owned - 1, heldTokens = rest })+      []       -> panic "removeOwnedToken: no held tokens"  -- | Add one new job to the end of the list of pending jobs. addJob :: TMVar () -> JobResources -> JobResources@@ -146,7 +170,7 @@   = Idle   -- | A thread is waiting for a token on the semaphore.   | Acquiring-    { activeWaitId   :: WaitId+    { activeThreadId :: ThreadId     , threadFinished :: TMVar (Maybe MC.SomeException) }  -- | Retrieve the 'TMVar' that signals if the current thread has finished,@@ -192,18 +216,31 @@       return ((), addFreeToken jobs)  --- | Release all tokens owned from the semaphore (to clean up--- the jobserver at the end).-cleanupJobserver :: Jobserver -> IO ()-cleanupJobserver (Jobserver { jSemaphore = sem-                            , jobs       = jobs_tvar })-  = do-    Jobs { tokensOwned = owned } <- readTVarIO jobs_tvar-    let toks_to_release = owned - 1-      -- Subtract off the implicit token: whoever spawned the ghc process-      -- in the first place is responsible for that token.-    releaseSemaphore sem toks_to_release+-- | Kill the current acquire thread, if any, and wait for it to exit.+--+-- Called from the jobserver loop's exit handler, which runs masked.+-- Relies on the invariant from 'acquireThread' that a forked child+-- always fills its 'threadFinished' TMVar before it dies; this is what+-- lets the 'takeTMVar' below terminate after the 'killThread'.+drainActiveChild :: Jobserver -> IO ()+drainActiveChild (Jobserver { activeChild = active_tvar }) = do+  mb <- readTVarIO active_tvar+  for_ mb $ \(tid, tmv) -> do+    killThread tid+    void $ atomically (takeTMVar tmv)+    atomically $ writeTVar active_tvar Nothing +-- | Release every token currently in 'heldTokens'.+--+-- Called from the jobserver loop's exit handler, which runs masked,+-- after 'drainActiveChild': no other thread is mutating 'JobResources'+-- at this point.+releaseAllHeld :: Jobserver -> IO ()+releaseAllHeld (Jobserver { jobs = jobs_tvar }) = do+  Jobs { heldTokens = toks } <- readTVarIO jobs_tvar+  forM_ toks $ \t ->+    void $ MC.try @_ @MC.SomeException (releaseSemaphoreToken t)+ -- | Dispatch the available tokens acquired from the semaphore -- to the pending jobs in the job server. dispatchTokens :: JobResources -> STM JobResources@@ -255,7 +292,7 @@   return a  renderJobResources :: String -> JobResources -> String-renderJobResources origin (Jobs own free pending) = showSDocUnsafe $ renderJSON $+renderJobResources origin (Jobs own free pending _heldToks) = showSDocUnsafe $ renderJSON $   JSObject [ ("name", JSString origin)            , ("owned", JSInt own)            , ("free", JSInt free)@@ -265,61 +302,68 @@  -- | Spawn a new thread that waits on the semaphore in order to acquire -- an additional token.+--+-- The child is forked masked so the only async-exception delivery point+-- is the interruptible 'waitOnSemaphore'; the STM commit afterwards then+-- always runs to completion, so 'threadFinished' is always filled.+--+-- The (tid, threadFinished) pair is also published to 'activeChild' so+-- shutdown can drain the child even after the in-loop 'JobserverState'+-- is gone. acquireThread :: Jobserver -> IO JobserverAction-acquireThread (Jobserver { jSemaphore = sem, jobs = jobs_tvar }) = do+acquireThread (Jobserver { jSemaphore = sem, jobs = jobs_tvar, activeChild = active_tvar }) = do     threadFinished_tmvar <- newEmptyTMVarIO-    let-      wait_result_action :: Either MC.SomeException Bool -> IO ()-      wait_result_action wait_res =+    tid <- MC.mask_ $ do+      tid <- forkIO $ do+        wait_res <- MC.try @_ @MC.SomeException $ waitOnSemaphore sem         tracedAtomically_ "acquire_thread" do           (r, jb) <- case wait_res of             Left (e :: MC.SomeException) -> do               return $ (Just e, Nothing)-            Right success -> do-              if success-                then do-                  modifyJobResources jobs_tvar \ jobs ->-                    return (Nothing, addToken jobs)-                else-                  return (Nothing, Nothing)+            Right tok -> do+              modifyJobResources jobs_tvar \ jobs ->+                return (Nothing, addToken tok jobs)           putTMVar threadFinished_tmvar r           return jb-    wait_id <- forkWaitOnSemaphoreInterruptible sem wait_result_action-    labelThread (waitingThreadId wait_id) "acquire_thread"-    return $ Acquiring { activeWaitId   = wait_id+      atomically $ writeTVar active_tvar (Just (tid, threadFinished_tmvar))+      return tid+    labelThread tid "acquire_thread"+    return $ Acquiring { activeThreadId = tid                        , threadFinished = threadFinished_tmvar }  -- | Spawn a thread to release ownership of one resource from the semaphore, -- provided we have spare resources and no pending jobs. releaseThread :: Jobserver -> IO JobserverAction-releaseThread (Jobserver { jSemaphore = sem, jobs = jobs_tvar }) = do+releaseThread (Jobserver { jobs = jobs_tvar }) = do   threadFinished_tmvar <- newEmptyTMVarIO   MC.mask_ do     -- Pre-release the resource so that another thread doesn't take control of it     -- just as we release the lock on the semaphore.-    still_ok_to_release+    mb_tok       <- tracedAtomically "pre_release" $          modifyJobResources jobs_tvar \ jobs ->            if guardRelease jobs-               -- TODO: should this also debounce?-           then return (True , removeOwnedToken $ removeFreeToken jobs)-           else return (False, jobs)-    if not still_ok_to_release-    then return Idle-    else do-      tid <- forkIO $ do-        x <- MC.try $ releaseSemaphore sem 1-        tracedAtomically_ "post-release" $ do-          (r, jobs) <- case x of-            Left (e :: MC.SomeException) -> do-              modifyJobResources jobs_tvar \ jobs ->-                return (Just e, addToken jobs)-            Right _ -> do-              return (Nothing, Nothing)-          putTMVar threadFinished_tmvar r-          return jobs-      labelThread tid "release_thread"-      return Idle+           then let (tok, jobs') = removeOwnedToken $ removeFreeToken jobs+                in return (Just tok, jobs')+           else return (Nothing, jobs)+    case mb_tok of+      Nothing ->+        -- Not OK to release: there are other pending jobs that could make use of the token.+        return Idle+      Just tok -> do+        tid <- forkIO $ do+          x <- MC.try @_ @MC.SomeException $ releaseSemaphoreToken tok+          tracedAtomically_ "post-release" $ do+            (r, jobs) <- case x of+              Left (e :: MC.SomeException) -> do+                modifyJobResources jobs_tvar \ jobs ->+                  return (Just e, addToken tok jobs)+              Right _ -> do+                return (Nothing, Nothing)+            putTMVar threadFinished_tmvar r+            return jobs+        labelThread tid "release_thread"+        return Idle  -- | When there are pending jobs but no free tokens, -- spawn a thread to acquire a new token from the semaphore.@@ -366,13 +410,14 @@ -- | Wait for an active thread to finish. Once it finishes: -- --  - set the 'JobserverAction' to 'Idle',+--  - clear the 'activeChild' handle, --  - update the number of capabilities to reflect the number --    of owned tokens from the semaphore. tryNoticeIdle :: JobserverOptions-              -> TVar JobResources+              -> Jobserver               -> JobserverState               -> STM (IO JobserverState)-tryNoticeIdle opts jobs_tvar jobserver_state+tryNoticeIdle opts (Jobserver { jobs = jobs_tvar, activeChild = active_tvar }) jobserver_state   | Just threadFinished_tmvar <- activeThread_maybe $ jobserverAction jobserver_state   = sync_num_caps (canChangeNumCaps jobserver_state) threadFinished_tmvar   | otherwise@@ -384,6 +429,7 @@     sync_num_caps can_change_numcaps_tvar threadFinished_tmvar = do       mb_ex <- takeTMVar threadFinished_tmvar       for_ mb_ex MC.throwM+      writeTVar active_tvar Nothing       Jobs { tokensOwned } <- readTVar jobs_tvar       can_change_numcaps <- readTVar can_change_numcaps_tvar       guard can_change_numcaps@@ -407,11 +453,11 @@               -> STM (IO JobserverState) tryStopThread jobs_tvar jsj = do   case jobserverAction jsj of-    Acquiring { activeWaitId = wait_id } -> do+    Acquiring { activeThreadId = tid } -> do      jobs <- readTVar jobs_tvar      guard $ null (jobsWaiting jobs)      return do-       interruptWaitOnSemaphore wait_id+       killThread tid        return $ jsj { jobserverAction = Idle }     _ -> retry @@ -433,30 +479,38 @@       action <- atomically $ asum $ (\x -> x s) <$>         [ tryRelease    sjs         , tryAcquire    opts sjs-        , tryNoticeIdle opts jobs_tvar+        , tryNoticeIdle opts sjs         , tryStopThread jobs_tvar         ]       s <- action       loop s --- | Create a new jobserver using the given semaphore handle.-makeJobserver :: SemaphoreName -> IO (AbstractSem, IO ())-makeJobserver sem_name = do-  semaphore <- openSemaphore sem_name+-- | Create a new jobserver using the given semaphore identifier.+makeJobserver :: SemaphoreIdentifier -> IO (AbstractSem, IO ())+makeJobserver sem_ident = do+  semaphore <- openSemaphore sem_ident >>= either MC.throwM pure   let     init_jobs =       Jobs { tokensOwned = 1            , tokensFree  = 1            , jobsWaiting = NilOL+           , heldTokens  = []            }   jobs_tvar <- newTVarIO init_jobs+  active_tvar <- newTVarIO Nothing   let     opts = defaultJobserverOptions -- TODO: allow this to be configured-    sjs = Jobserver { jSemaphore = semaphore-                    , jobs       = jobs_tvar }+    sjs = Jobserver { jSemaphore  = semaphore+                    , jobs        = jobs_tvar+                    , activeChild = active_tvar }   loop_finished_mvar <- newEmptyMVar   loop_tid <- forkIOWithUnmask \ unmask -> do     r <- try $ unmask $ jobserverLoop opts sjs+    -- Always-run exit handler: any child the loop spawned is still alive+    -- in its own thread, so drain it before touching jobs_tvar. No one+    -- else can mutate the resources once both are dead.+    drainActiveChild sjs+    releaseAllHeld sjs     putMVar loop_finished_mvar $       case r of         Left e@@ -470,8 +524,8 @@     acquireSem = acquireJob jobs_tvar     releaseSem = releaseJob jobs_tvar     cleanupSem = do-      -- this is interruptible-      cleanupJobserver sjs+      -- Trigger the loop's exit handler; it drains the active child and+      -- releases all held tokens, then signals loop_finished_mvar.       killThread loop_tid       mb_ex <- takeMVar loop_finished_mvar       for_ mb_ex MC.throwM@@ -480,12 +534,12 @@  -- | Implement an abstract semaphore using a semaphore 'Jobserver' -- which queries the system semaphore of the given name for resources.-runJSemAbstractSem :: SemaphoreName         -- ^ the system semaphore to use+runJSemAbstractSem :: SemaphoreIdentifier   -- ^ the semaphore identifier (from @-jsem@)                    -> (AbstractSem -> IO a) -- ^ the operation to run                                             -- which requires a semaphore                    -> IO a-runJSemAbstractSem sem action = MC.mask \ unmask -> do-  (abs, cleanup) <- makeJobserver sem+runJSemAbstractSem sem_ident action = MC.mask \ unmask -> do+  (abs, cleanup) <- makeJobserver sem_ident   r <- try $ unmask $ action abs   case r of     Left (e1 :: MC.SomeException) -> do@@ -520,8 +574,13 @@ is increased, the token is immediately reused (see `modifyJobResources`).  The `jobServerLoop` interacts with the system semaphore: when there are pending-jobs, `acquireThread` blocks, waiting for a token from the semaphore. Once a-token is obtained, it increases the owned count.+jobs, `acquireThread` forks a child that calls the interruptible+`waitOnSemaphore`. The child is forked in the masked state, so the only place+an async exception can be delivered is the wait itself; once the wait returns,+the child's STM commit always completes, recording either the new token in+`heldTokens` or the failure exception in `threadFinished`. The (tid, tmvar)+pair is also published in `activeChild` so the loop's exit handler can drain+the child on shutdown even after the in-loop `JobserverState` is gone.  When GHC has free tokens (tokens from the semaphore that it is not using), no pending jobs, and the debounce has expired, then `releaseThread` will@@ -534,6 +593,12 @@ (as it would not be used to do any work, and not be returned until the debounce). We only need to kill `acquireJob`, because `releaseJob` never blocks. +Shutdown starts with `killThread loop_tid`. The loop's exit handler then+runs `drainActiveChild` followed by `releaseAllHeld`; only then does the+loop signal `loop_finished_mvar`. This sequence makes the heldTokens+snapshot consistent because no other thread can mutate it once the loop and+its child are both dead.+ Note [Eventlog Messages for jsem] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It can be tricky to verify that the work is shared adequately across different@@ -543,3 +608,5 @@ GitHub repo (https://github.com/mpickering/ghc-jsem-analyse).  -}++#endif
GHC/Driver/Phases.hs view
@@ -258,7 +258,7 @@ -- the GHC-compiled code will run objish_suffixes platform = case platformOS platform of   OSMinGW32 -> [ "o", "O", "obj", "OBJ" ]-  _         -> [ "o" ]+  _         -> [ "o", "dyn_o"]  dynlib_suffixes :: Platform -> [String] dynlib_suffixes platform = case platformOS platform of
GHC/Driver/Pipeline/Execute.hs view
@@ -42,6 +42,7 @@ import GHC.Utils.TmpFs import GHC.Platform import Data.List (intercalate, isInfixOf)+import qualified Data.List.NonEmpty as NE import GHC.Unit.Env import GHC.Utils.Error import Data.Maybe@@ -68,6 +69,7 @@ import GHC.Platform.Ways import GHC.Driver.LlvmConfigCache (readLlvmConfigCache) import GHC.CmmToLlvm.Config (LlvmTarget (..), LlvmConfig (..))+import GHC.CmmToLlvm.Version.Type (LlvmVersion (..)) import {-# SOURCE #-} GHC.Driver.Pipeline (compileForeign, compileEmptyStub) import GHC.Settings import System.IO@@ -228,8 +230,9 @@           1 -> "-O1"           _ -> "-O2" -        defaultOptions = map GHC.SysTools.Option . concatMap words . snd-                         $ unzip (llvmOptions llvm_config dflags)+    llvm_version <- figureLlvmVersion logger dflags+    let defaultOptions = map GHC.SysTools.Option . concatMap words . snd+                         $ unzip (llvmOptions llvm_config llvm_version dflags)         optFlag = if null (getOpts dflags opt_lc)                   then map GHC.SysTools.Option $ words llvmOpts                   else []@@ -264,8 +267,9 @@                     Nothing -> panic ("runPhase LlvmOpt: llvm-passes file "                                       ++ "is missing passes for level "                                       ++ show optIdx)-        defaultOptions = map GHC.SysTools.Option . concat . fmap words . fst-                         $ unzip (llvmOptions llvm_config dflags)+    llvm_version <- figureLlvmVersion logger dflags+    let defaultOptions = map GHC.SysTools.Option . concat . fmap words . fst+                         $ unzip (llvmOptions llvm_config llvm_version dflags)          -- don't specify anything if user has specified commands. We do this         -- for opt but not llc since opt is very specifically for optimisation@@ -722,10 +726,10 @@   -- the object file for one module.)   -- Note the nasty duplication with the same computation in compileFile above   location <- mkOneShotModLocation pipe_env dflags src_flavour mod_name-  let o_file = ml_obj_file location -- The real object file-      hi_file = ml_hi_file location-      hie_file = ml_hie_file location-      dyn_o_file = ml_dyn_obj_file location+  let o_file = ml_obj_file_ospath location -- The real object file+      hi_file = ml_hi_file_ospath location+      hie_file = ml_hie_file_ospath location+      dyn_o_file = ml_dyn_obj_file_ospath location    src_hash <- getFileHash (basename <.> suff)   hi_date <- modificationTimeIfExists hi_file@@ -959,12 +963,21 @@ -- | LLVM Options. These are flags to be passed to opt and llc, to ensure -- consistency we list them in pairs, so that they form groups. llvmOptions :: LlvmConfig+            -> Maybe LlvmVersion             -> DynFlags             -> [(String, String)]  -- ^ pairs of (opt, llc) arguments-llvmOptions llvm_config dflags =+llvmOptions llvm_config llvm_version dflags =        [("-relocation-model=" ++ rmodel         ,"-relocation-model=" ++ rmodel) | not (null rmodel)] +    -- Both llc/opt need these flags for split sections+    ++ [ ("--data-sections", "--data-sections")+       | gopt Opt_SplitSections dflags+       ]+    ++ [ ("--function-sections", "--function-sections")+       | gopt Opt_SplitSections dflags+       ]+     -- Additional llc flags     ++ [("", "-mcpu=" ++ mcpu)   | not (null mcpu)                                  , not (any (isInfixOf "-mcpu") (getOpts dflags opt_lc)) ]@@ -1001,6 +1014,10 @@               ++ ["+sse2"    | isSse2Enabled platform   ]               ++ ["+sse"     | isSseEnabled platform    ]               ++ ["+avx512f" | isAvx512fEnabled dflags  ]+              ++ ["+evex512" | isAvx512fEnabled dflags+                             , maybe False (>= LlvmVersion (18 NE.:| [])) llvm_version ]+                   -- +evex512 is recognized by LLVM 18 or newer and needed on macOS (#26410).+                   -- It may become deprecated in a future LLVM version, though.               ++ ["+avx2"    | isAvx2Enabled dflags     ]               ++ ["+avx"     | isAvxEnabled dflags      ]               ++ ["+avx512cd"| isAvx512cdEnabled dflags ]
GHC/Driver/Session.hs view
@@ -280,6 +280,9 @@  import GHC.SysTools.BaseDir ( expandToolDir, expandTopDir ) +import System.Semaphore ( getSemaphoreProtocolVersion, semaphoreVersion )++ import Data.IORef import Control.Arrow ((&&&)) import Control.Monad@@ -293,8 +296,11 @@ import qualified Data.List.NonEmpty as NE import qualified Data.Map as Map import qualified Data.Set as Set+import GHC.Types.Unique.Set import Data.Word import System.FilePath+import qualified GHC.Data.OsPath as OsPath+ import Text.ParserCombinators.ReadP hiding (char) import Text.ParserCombinators.ReadP as R @@ -2047,7 +2053,7 @@ package_flags_deps = [         ------- Packages ----------------------------------------------------     make_ord_flag defFlag "package-db"-      (HasArg (addPkgDbRef . PkgDbPath))+      (HasArg (addPkgDbRef . PkgDbPath . OsPath.unsafeEncodeUtf))   , make_ord_flag defFlag "clear-package-db"      (NoArg clearPkgDb)   , make_ord_flag defFlag "no-global-package-db"  (NoArg removeGlobalPkgDb)   , make_ord_flag defFlag "no-user-package-db"    (NoArg removeUserPkgDb)@@ -2057,7 +2063,7 @@       (NoArg (addPkgDbRef UserPkgDb))     -- backwards compat with GHC<=7.4 :   , make_dep_flag defFlag "package-conf"-      (HasArg $ addPkgDbRef . PkgDbPath) "Use -package-db instead"+      (HasArg $ addPkgDbRef . PkgDbPath . OsPath.unsafeEncodeUtf) "Use -package-db instead"   , make_dep_flag defFlag "no-user-package-conf"       (NoArg removeUserPkgDb)              "Use -no-user-package-db instead"   , make_ord_flag defGhcFlag "package-name"       (HasArg $ \name ->@@ -2391,6 +2397,7 @@   Opt_WarnRuleLhsEqualities -> warnSpec x   Opt_WarnUnusableUnpackPragmas -> warnSpec x   Opt_WarnPatternNamespaceSpecifier -> warnSpec x+  Opt_WarnSemaphoreOpenFailure -> warnSpec x  warningGroupsDeps :: [(Deprecation, FlagSpec WarningGroup)] warningGroupsDeps = map mk warningGroups@@ -2507,6 +2514,7 @@    -- load all targets on GHCi startup   flagGhciSpec "load-initial-targets"         Opt_GhciDoLoadTargets,+  flagGhciSpec "import-loaded-targets"        Opt_GhciImportLoadedTargets,    flagSpec "helpful-errors"                   Opt_HelpfulErrors,   flagSpec "hpc"                              Opt_Hpc,@@ -3153,7 +3161,7 @@  addHiddenModule :: String -> DynP () addHiddenModule p =-  upd (\s -> s{ hiddenModules  = Set.insert (mkModuleName p) (hiddenModules s) })+  upd (\s -> s{ hiddenModules  = addOneToUniqSet (hiddenModules s) (mkModuleName p) })  addReexportedModule :: String -> DynP () addReexportedModule p =@@ -3249,7 +3257,7 @@ parseEnvFile envfile = mapM_ parseEntry . lines   where     parseEntry str = case words str of-      ("package-db": _)     -> addPkgDbRef (PkgDbPath (envdir </> db))+      ("package-db": _)     -> addPkgDbRef (PkgDbPath (OsPath.unsafeEncodeUtf (envdir </> db)))         -- relative package dbs are interpreted relative to the env file         where envdir = takeDirectory envfile               db     = drop 11 str@@ -3481,6 +3489,8 @@        ("Support dynamic-too",         showBool $ not isWindows),        -- Whether or not we support the @-j@ flag with @--make@.        ("Support parallel --make",     "YES"),+       -- The semaphore protocol version supported by @-jsem@.+       ("Semaphore version",           show (getSemaphoreProtocolVersion semaphoreVersion)),        -- Whether or not we support "Foo from foo-0.1-XXX:Foo" syntax in        -- installed package info.        ("Support reexported-modules",  "YES"),
GHC/Driver/Session/Units.hs view
@@ -131,16 +131,14 @@   let home_units = HUG.allUnits initial_home_graph    home_unit_graph <- forM initial_home_graph $ \homeUnitEnv -> do-    let cached_unit_dbs = homeUnitEnv_unit_dbs homeUnitEnv-        hue_flags = homeUnitEnv_dflags homeUnitEnv+    let hue_flags = homeUnitEnv_dflags homeUnitEnv         dflags = homeUnitEnv_dflags homeUnitEnv-    (dbs,unit_state,home_unit,mconstants) <- liftIO $ State.initUnits logger hue_flags cached_unit_dbs home_units+    (unit_state,home_unit,mconstants) <- liftIO $ State.initUnits logger hue_flags (hscUIC hsc_env) home_units      updated_dflags <- liftIO $ updatePlatformConstants dflags mconstants     emptyHpt <- liftIO $ emptyHomePackageTable     pure $ HomeUnitEnv       { homeUnitEnv_units = unit_state-      , homeUnitEnv_unit_dbs = Just dbs       , homeUnitEnv_dflags = updated_dflags       , homeUnitEnv_hpt = emptyHpt       , homeUnitEnv_home_unit = Just home_unit@@ -149,9 +147,16 @@   checkUnitCycles initial_dflags home_unit_graph    let dflags = homeUnitEnv_dflags $ HUG.unitEnv_lookup mainUnitId home_unit_graph-  unitEnv <- assertUnitEnvInvariant <$> (liftIO $ initUnitEnv mainUnitId home_unit_graph (ghcNameVersion dflags) (targetPlatform dflags))-  let final_hsc_env = hsc_env { hsc_unit_env = unitEnv }+  newUnitEnv <-  do+    env <- liftIO $ initUnitEnv mainUnitId home_unit_graph (ghcNameVersion dflags) (targetPlatform dflags)+    -- We need to reuse the 'UnitIndexCache' as we used it above in 'initUnits'.+    -- See Note [Sharing 'UnitInfo's across the 'UnitEnv'] why this must be shared.+    pure $ assertUnitEnvInvariant $ env+      { ue_uic = hscUIC hsc_env+      } +  let final_hsc_env = hsc_env { hsc_unit_env = newUnitEnv }+   GHC.setSession final_hsc_env    -- if we have no haskell sources from which to do a dependency@@ -241,7 +246,7 @@   unitEnvList <- forM unitDflags $ \dflags -> do     emptyHpt <- emptyHomePackageTable     let newInternalUnitEnv =-          HUG.mkHomeUnitEnv emptyUnitState Nothing dflags emptyHpt Nothing+          HUG.mkHomeUnitEnv emptyUnitState dflags emptyHpt Nothing     return (homeUnitId_ dflags, newInternalUnitEnv)   let activeUnit = fst $ NE.head unitEnvList   return (HUG.hugFromList (NE.toList unitEnvList), activeUnit)
GHC/Hs/Binds.hs view
@@ -734,13 +734,14 @@ data ActivationAnn   = ActivationAnn {       aa_openc  :: EpToken "[",+      aa_phase  :: SourceText,       aa_closec :: EpToken "]",       aa_tilde  :: Maybe (EpToken "~"),       aa_val    :: Maybe EpaLocation     } deriving (Data, Eq)  instance NoAnn ActivationAnn where-  noAnn = ActivationAnn noAnn noAnn noAnn noAnn+  noAnn = ActivationAnn noAnn NoSourceText noAnn noAnn noAnn   -- | Optional namespace specifier for fixity signatures,
GHC/Hs/Doc.hs view
@@ -50,6 +50,7 @@ import GHC.Hs.Extension import GHC.Types.Unique.Map import Data.List (sortBy)+import Data.Function  import GHC.Hs.DocString @@ -88,7 +89,7 @@ instance Binary a => Binary (WithHsDocIdentifiers a GhcRn) where   put_ bh (WithHsDocIdentifiers s ids) = do     put_ bh s-    put_ bh $ BinLocated <$> ids+    put_ bh $ BinLocated <$> (sortBy  (stableNameCmp `on` getName) ids)   get bh =     liftA2 WithHsDocIdentifiers (get bh) (fmap unBinLocated <$> get bh) 
GHC/Hs/Expr.hs view
@@ -2297,6 +2297,7 @@           { implicit_lift_bind_lvl :: S.Set ThLevelIndex           , implicit_lift_used_lvl :: ThLevelIndex           , implicit_lift_gre :: Maybe GlobalRdrElt+            -- ^ Nothing iff 'LevelCheckReason' is 'LevelCheckInstance'           , implicit_lift_lid :: LIdOccP GhcRn           } 
GHC/Hs/Instances.hs view
@@ -21,6 +21,21 @@  -- UndecidableInstances ? +{- Note [Data.Data instances for GHC AST Types]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+We give all of the frontend types and their instantiations (HsSyn) and+some other types Data.Data instances. There are two main motivations to+do so:++* For users of the GHC API it allows to write Generic code over the GHC AST.+* GHC itself has a few uses of these as well:+    * In the showAstData, showAstDataFull helpers to print a representation of+      the actual AST using it's constructors rather than just user facing pretty printing.+    * It's used to some degree for HIE file generation in the ToHIE instances.+    * TH serialization uses it for serialization of Annotations (GHC.Serialized)+    * Some of the dump flags use showAstData to produce the actual dump output.+-}+ import Data.Data hiding ( Fixity )  import GHC.Prelude
GHC/HsToCore/Arrows.hs view
@@ -554,7 +554,7 @@           in_ty = envStackType env_ids stack_ty'           discrims = map nlHsVar arg_ids       (discrim_vars, matching_code)-        <- matchWrapper (ArrowMatchCtxt match_ctxt) (Just discrims) match'+        <- matchWrapper (ArrowMatchCtxt match_ctxt) (Just (map Var arg_ids)) match'       core_body <- flip (bind_vars discrim_vars) matching_code <$>         traverse dsLExpr discrims 
GHC/HsToCore/Breakpoints.hs view
@@ -15,7 +15,7 @@ -- See Note [ModBreaks vs InternalModBreaks] and Note [Breakpoint identifiers] module GHC.HsToCore.Breakpoints   ( -- * ModBreaks-    mkModBreaks, ModBreaks(..)+    mkModBreaks, ModBreaks(..), modBreaks_locs      -- ** Re-exports BreakpointId   , BreakpointId(..), BreakTickIndex@@ -25,46 +25,12 @@ import Data.Array  import GHC.HsToCore.Ticks (Tick (..))+import GHC.HsToCore.Breakpoints.Types import GHC.Data.SizedSeq-import GHC.Types.SrcLoc (SrcSpan)-import GHC.Types.Name (OccName)-import GHC.Types.Tickish (BreakTickIndex, BreakpointId(..)) import GHC.Unit.Module (Module) import GHC.Utils.Outputable import Data.List (intersperse)------------------------------------------------------------------------------------- ModBreaks------------------------------------------------------------------------------------- | All the information about the source-relevant breakpoints for a module------ This information is constructed once during desugaring (with `mkModBreaks`)--- from breakpoint ticks and fixed/unchanged from there on forward. It could be--- exported as an abstract datatype because it should never be updated after--- construction, only queried.------ The arrays can be indexed using the int in the corresponding 'BreakpointId'--- (i.e. the 'BreakpointId' whose 'Module' matches the 'Module' corresponding--- to these 'ModBreaks') with the accessors 'modBreaks_locs', 'modBreaks_vars',--- and 'modBreaks_decls'.-data ModBreaks-   = ModBreaks-   { modBreaks_locs   :: !(Array BreakTickIndex SrcSpan)-        -- ^ An array giving the source span of each breakpoint.-   , modBreaks_vars   :: !(Array BreakTickIndex [OccName])-        -- ^ An array giving the names of the free variables at each breakpoint.-   , modBreaks_decls  :: !(Array BreakTickIndex [String])-        -- ^ An array giving the names of the declarations enclosing each breakpoint.-        -- See Note [Field modBreaks_decls]-   , modBreaks_ccs    :: !(Array BreakTickIndex (String, String))-        -- ^ Array pointing to cost centre info for each breakpoint;-        -- actual 'CostCentre' allocation is done at link-time.-   , modBreaks_module :: !Module-        -- ^ The module to which this ModBreaks is associated.-        -- We also cache this here for internal sanity checks.-   }-+import GHC.Utils.Binary (BinSrcSpan(BinSrcSpan)) -- | Initialize memory for breakpoint data that is shared between the bytecode -- generator and the interpreter. --@@ -91,7 +57,7 @@                 ]           | otherwise = listArray (0, -1) []      in ModBreaks-      { modBreaks_locs   = locsTicks+      { modBreaks_locs_  = fmap BinSrcSpan locsTicks       , modBreaks_vars   = varsTicks       , modBreaks_decls  = declsTicks       , modBreaks_ccs    = ccs
+ GHC/HsToCore/Breakpoints/Types.hs view
@@ -0,0 +1,81 @@+{-# LANGUAGE RecordWildCards #-}++-- | Information attached to Breakpoints generated from Ticks+--+-- The breakpoint information stored in 'ModBreaks' is generated during+-- desugaring from the ticks annotating the source expressions.+--+-- This information can be queried per-breakpoint using the 'BreakpointId'+-- datatype, which indexes tick-level breakpoint information.+--+-- 'ModBreaks' and 'BreakpointId's are not to be confused with+-- 'InternalModBreaks' and 'InternalBreakId's. The latter are constructed+-- during bytecode generation and can be found in 'GHC.ByteCode.Breakpoints'.+--+-- See Note [ModBreaks vs InternalModBreaks] and Note [Breakpoint identifiers]+module GHC.HsToCore.Breakpoints.Types+  ( -- * ModBreaks+    ModBreaks(..), modBreaks_locs++    -- ** Re-exports BreakpointId+  , BreakpointId(..), BreakTickIndex+  ) where++import GHC.Prelude+import Data.Array++import GHC.Types.SrcLoc (SrcSpan)+import GHC.Types.Name (OccName)+import GHC.Types.Tickish (BreakTickIndex, BreakpointId(..))+import GHC.Unit.Module (Module)+import Data.Coerce+import GHC.Utils.Binary (BinSrcSpan(..), Binary(..))+import Control.DeepSeq++--------------------------------------------------------------------------------+-- ModBreaks+--------------------------------------------------------------------------------++-- | All the information about the source-relevant breakpoints for a module+--+-- This information is constructed once during desugaring (with `mkModBreaks`)+-- from breakpoint ticks and fixed/unchanged from there on forward. It could be+-- exported as an abstract datatype because it should never be updated after+-- construction, only queried.+--+-- The arrays can be indexed using the int in the corresponding 'BreakpointId'+-- (i.e. the 'BreakpointId' whose 'Module' matches the 'Module' corresponding+-- to these 'ModBreaks') with the accessors 'modBreaks_locs', 'modBreaks_vars',+-- and 'modBreaks_decls'.+data ModBreaks+   = ModBreaks+   { modBreaks_locs_   :: !(Array BreakTickIndex BinSrcSpan)+        -- ^ An array giving the source span of each breakpoint.+   , modBreaks_vars   :: !(Array BreakTickIndex [OccName])+        -- ^ An array giving the names of the free variables at each breakpoint.+   , modBreaks_decls  :: !(Array BreakTickIndex [String])+        -- ^ An array giving the names of the declarations enclosing each breakpoint.+        -- See Note [Field modBreaks_decls]+   , modBreaks_ccs    :: !(Array BreakTickIndex (String, String))+        -- ^ Array pointing to cost centre info for each breakpoint;+        -- actual 'CostCentre' allocation is done at link-time.+   , modBreaks_module :: !Module+        -- ^ The module to which this ModBreaks is associated.+        -- We also cache this here for internal sanity checks.+   }++modBreaks_locs :: ModBreaks -> Array BreakTickIndex SrcSpan+modBreaks_locs = coerce . modBreaks_locs_++instance Binary ModBreaks where+  get bh = ModBreaks <$> get bh <*> get bh <*> get bh <*> get bh <*> get bh++  put_ bh ModBreaks {..} =+    put_ bh modBreaks_locs_+      *> put_ bh modBreaks_vars+      *> put_ bh modBreaks_decls+      *> put_ bh modBreaks_ccs+      *> put_ bh modBreaks_module++instance NFData ModBreaks where+  rnf (ModBreaks a b c d e) = rnf a `seq` rnf b `seq` rnf c `seq` rnf d `seq` rnf e
GHC/HsToCore/Docs.hs view
@@ -175,7 +175,7 @@     moduleExport alias avails =         DsiModExport (nubSortNE orig_names) (sortAvails (nubAvails avails))       where-        orig_names = M.findWithDefault aliasErr alias aliasMap+        orig_names = fromMaybe aliasErr (lookupUniqMap aliasMap alias)         aliasErr = error $ "mkDocStructureFromExportList: "                            ++ (moduleNameString . moduleName) mdl                            ++ ": Can't find alias " ++ moduleNameString alias@@ -185,9 +185,9 @@                     NonEmpty.toList      -- Map from aliases to true module names.-    aliasMap :: Map ModuleName (NonEmpty ModuleName)+    aliasMap :: UniqMap ModuleName (NonEmpty ModuleName)     aliasMap =-        M.fromListWith (S.<>) $+        listToUniqMap_C (S.<>) $           (this_mdl_name, this_mdl_name :| [])           : (flip concatMap (M.toList imported) $ \(mdl, imvs) ->               [(imv_name imv, moduleName mdl :| []) | imv <- imvs])
GHC/HsToCore/Expr.hs view
@@ -413,7 +413,7 @@  dsExpr (HsCase ctxt discrim matches)   = do { core_discrim <- dsLExpr discrim-       ; ([discrim_var], matching_code) <- matchWrapper ctxt (Just [discrim]) matches+       ; ([discrim_var], matching_code) <- matchWrapper ctxt (Just [core_discrim]) matches        ; return (bindNonRec discrim_var core_discrim matching_code) }  -- Pepe: The binds are in scope in the body but NOT in the binding group@@ -695,6 +695,15 @@ ds_app (XExpr (HsRecSelTc (FieldOcc { foLabel = L _ sel_id }))) _hs_args core_args   = ds_app_rec_sel sel_id sel_id core_args +ds_app (XExpr (ExpandedThingTc _orig e)) hs_args core_args+  = ds_app e hs_args core_args+  -- NB: this is important for the 'getField' case of 'ds_app_var', which needs+  -- to see all type arguments to 'getField' at once, while for record field+  -- projections such as (.fld) we may get:+  --+  --   XExpr (ExpandedThingTc (.fld) (getField @Symbol @LiftedRep @LiftedRep "fld"))+  --     `HsAppType` rec_ty `HsAppType` fld+ ds_app (HsVar _ lfun) hs_args core_args   = ds_app_var lfun hs_args core_args @@ -710,8 +719,10 @@   -----------------------   -- Deal with getField applications. General form:   --   getField-  --     @GHC.Types.Symbol                        {k}-  --     @"sel"                                   x_ty+  --     @Symbol                                  {k}+  --     @LiftedRep                               {r_rep}+  --     @LiftedRep                               {a_rep}+  --     @"sel"                                   fld   --     @T                                       r_ty   --     @Int                                     a_ty   --     ($dHasField :: HasField "sel" T Int)     dict@@ -1247,11 +1258,11 @@     do { fam_inst_envs <- dsGetFamInstEnvs        ; let norm_elt_ty = topNormaliseType fam_inst_envs elt_ty              supressible_ty =-               isUnitTy norm_elt_ty || isAnyTy norm_elt_ty || isZonkAnyTy norm_elt_ty+               isUnitTy norm_elt_ty || isAnyTy norm_elt_ty || isUnusedTypeTy norm_elt_ty          -- Warn about discarding things in 'monadic' binding,          -- however few types are excluded:          --   * Unit type `()`-         --   * `ZonkAny` or `Any` type see (Any8) of Note [Any types]+         --   * `UnusedType` or `Any` type see (Any5) of Note [The types Any and UnusedType]        ; if warn_unused && not supressible_ty          then diagnosticDs (DsUnusedDoBind rhs elt_ty)          else
GHC/HsToCore/Foreign/C.hs view
@@ -328,37 +328,68 @@ toCName :: Id -> String toCName i = showSDocOneLine defaultSDocContext (pprCode (ppr (idName i))) +{- Note [Collapsing void pointer chains]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+When translating Haskell types like (Ptr (Ptr Abstract)) to C types for capi+wrappers, where Abstract has no CType annotation, naively we would produce+"void**". This is problematic because in C, only void* has implicit conversion+to any pointer type.+Modern compilers (gcc, clang) treat -Wincompatible-pointer-types as an error+by default (#26852), causing compilation failures for capi wrappers.++The fix is to collapse void pointer chains: whenever the inner type of a+Ptr/FunPtr resolves to void (i.e. the Haskell type has no known C+representation), we return void* instead of void**, void***, etc.+This works because void* implicitly converts to any pointer type in C.++Examples:+  Ptr Abstract              => void*+  Ptr (Ptr Abstract)        => void*   (used to be void**)+  Ptr (Ptr (Ptr Abstract))  => void*+  Ptr (Ptr CInt)            => int**   (CInt has CType "int", don't collapse)+-}++-- | See Note [Collapsing void pointer chains] toCType :: Type -> (Maybe Header, SDoc)-toCType = f False-    where f voidOK t-           -- First, if we have (Ptr t) of (FunPtr t), then we need to+toCType t = case f False t of+              (mh, _, cType) -> (mh, cType)+    where+      -- The Bool in the return type indicates whether the C type is+      -- "void" due to an unknown Haskell type (True = void-based).+      f :: Bool -> Type -> (Maybe Header, Bool, SDoc)+      f voidOK t+           -- First, if we have (Ptr t) or (FunPtr t), then we need to            -- convert t to a C type and put a * after it. If we don't            -- know a type for t, then "void" is fine, though.+           -- If the inner type is void-based, we collapse the pointer+           -- chain to just "void*". See Note [Collapsing void pointer chains].            | Just (ptr, [t']) <- splitTyConApp_maybe t            , tyConName ptr `elem` [ptrTyConName, funPtrTyConName]               = case f True t' of-                (mh, cType') ->-                    (mh, cType' <> char '*')+                (mh, True, _) ->+                    (mh, True, text "void*")+                (mh, False, cType') ->+                    (mh, False, cType' <> char '*')            -- Otherwise, if we have a type constructor application, then            -- see if there is a C type associated with that constructor.            -- Note that we aren't looking through type synonyms or            -- anything, as it may be the synonym that is annotated.            | Just tycon <- tyConAppTyConPicky_maybe t-           , Just (CType _ mHeader (_,cType)) <- tyConCType_maybe tycon-              = (mHeader, ftext cType)+           , Just (CType _ mHeader (_, cType)) <- tyConCType_maybe tycon+              = (mHeader, False, ftext cType)            -- If we don't know a C type for this type, then try looking            -- through one layer of type synonym etc.            | Just t' <- coreView t               = f voidOK t'-          -- Handle 'UnliftedFFITypes' argument+           -- Handle 'UnliftedFFITypes' argument            | Just tyCon <- tyConAppTyConPicky_maybe t            , isPrimTyCon tyCon            , Just cType <- ppPrimTyConStgType tyCon-           = (Nothing, text cType)+           = (Nothing, False, text cType)             -- Otherwise we don't know the C type. If we are allowing            -- void then return that; otherwise something has gone wrong.-           | voidOK = (Nothing, text "void")+           | voidOK = (Nothing, True, text "void")            | otherwise               = pprPanic "toCType" (ppr t) 
GHC/HsToCore/Foreign/Wasm.hs view
@@ -225,6 +225,25 @@ the implementation of JSFFI imports and exports (rts_mkJSVal/rts_getJSVal). +We don't support unboxed FFI types like Int# etc. But we do support+one kind of unlifted FFI type for JSFFI import arguments:+ByteArray#/MutableByteArray#. The semantics is the same in C: the+pointer to the ByteArray# payload is passed instead of the ByteArray#+closure itself. This allows efficient zero-copy data exchange between+Haskell and JavaScript using unpinned ByteArray#, and the following+conditions must be met:++- The JSFFI import itself must be a sync import marked as unsafe+- The JavaScript code must not re-enter Haskell when a ByteArray# is+  passed as argument++There's no magic in the handling of ByteArray#/MutableByteArray#+arguments. When generating C stub, we treat them like Ptr that points+to the payload, just without the rts_getPtr() unboxing call. After+lowering to C import, the backend takes care of adding the offset, see+add_shim in GHC.StgToCmm.Foreign and+Note [Unlifted boxed arguments to foreign calls].+ Now, each sync import calls a generated C function with a unique symbol. The C function uses rts_get* to unbox the arguments, call into JavaScript, then boxes the result with rts_mk* and returns it to@@ -518,8 +537,9 @@     cfun_ret       | res_ty `eqType` unitTy = cfun_call_import <> semi       | otherwise = text "return" <+> cfun_call_import <> semi-    cfun_make_arg arg_ty arg_val =-      text ("rts_get" ++ ffiType arg_ty) <> parens arg_val+    cfun_make_arg arg_ty arg_val+      | isByteArrayPrimTy arg_ty = arg_val+      | otherwise = text ("rts_get" ++ ffiType arg_ty) <> parens arg_val     cfun_make_ret ret_val       | res_ty `eqType` unitTy = ret_val       | otherwise =@@ -544,7 +564,11 @@       | res_ty `eqType` unitTy = text "void"       | otherwise = text "HaskellObj"     cfun_arg_list =-      [text "HaskellObj" <+> char 'a' <> int n | n <- [1 .. length arg_tys]]+      [ text (if isByteArrayPrimTy arg_ty then "HsPtr" else "HaskellObj")+          <+> char 'a'+          <> int n+      | (arg_ty, n) <- zip arg_tys [1 ..]+      ]     cfun_args = case cfun_arg_list of       [] -> text "void"       _ -> hsep $ punctuate comma cfun_arg_list@@ -747,8 +771,18 @@   n <- lookupOrig (mkGhcInternalModule m) (mkTcOcc t)   dsLookupTyCon n +isByteArrayPrimTy :: Type -> Bool+isByteArrayPrimTy ty+  | Just tc <- tyConAppTyCon_maybe ty,+    tc == byteArrayPrimTyCon || tc == mutableByteArrayPrimTyCon =+      True+  | otherwise =+      False+ ffiType :: Type -> String-ffiType = occNameString . getOccName . fst . splitTyConApp+ffiType ty+  | isByteArrayPrimTy ty = "Ptr"+  | otherwise = occNameString $ getOccName $ tyConAppTyCon ty  commonCDecls :: SDoc commonCDecls =
GHC/HsToCore/Match.hs view
@@ -762,7 +762,7 @@  matchWrapper   :: HsMatchContextRn                  -- ^ For shadowing warning messages-  -> Maybe [LHsExpr GhcTc]             -- ^ Scrutinee(s)+  -> Maybe [CoreExpr]                  -- ^ Already-desugared scrutinee(s)                                        -- see Note [matchWrapper scrutinees]   -> MatchGroup GhcTc (LHsExpr GhcTc)  -- ^ Matches being desugared   -> DsM ([Id], CoreExpr)              -- ^ Results (usually passed to 'match')@@ -818,7 +818,7 @@                -- pmc for pattern synonyms              -- See Note [Long-distance information] in GHC.HsToCore.Pmc-            then addHsScrutTmCs (concat scrs) new_vars $+            then addCoreScrutTmCs (concat scrs) new_vars $                  pmcMatches origin (DsMatchContext ctxt locn) new_vars matches              -- When we're not doing PM checks on the match group,
GHC/HsToCore/Match.hs-boot view
@@ -16,7 +16,7 @@  matchWrapper         :: HsMatchContextRn-        -> Maybe [LHsExpr GhcTc]+        -> Maybe [CoreExpr]         -> MatchGroup GhcTc (LHsExpr GhcTc)         -> DsM ([Id], CoreExpr) 
GHC/HsToCore/Pmc.hs view
@@ -39,7 +39,7 @@         isMatchContextPmChecked, isMatchContextPmChecked_SinglePat,          -- See Note [Long-distance information]-        addTyCs, addCoreScrutTmCs, addHsScrutTmCs, getLdiNablas,+        addTyCs, addCoreScrutTmCs, getLdiNablas,         getNFirstUncovered     ) where @@ -63,7 +63,6 @@ import GHC.Types.Var (EvVar, Var (..)) import GHC.Types.Id.Info import GHC.Tc.Utils.TcType (evVarPred)-import {-# SOURCE #-} GHC.HsToCore.Expr (dsLExpr) import GHC.HsToCore.Monad import GHC.Data.Bag import GHC.Data.OrdList@@ -357,6 +356,10 @@   the (IRS6) warning in the typechecker for a `HasField` constraint that   arises from a record-dot HsGetField occurrence.  Happily, this is easy to do   by looking at its `CtOrigin`. Tested in T24891.++  The same applies for record field projection operators such as (.fld) and+  (.fld1.fld2), which have different 'CtOrigin's. The 'isHasFieldOrigin'+  function catches those as well. Tested in T26686. -}  pmcRecSel :: Id       -- ^ Id of the selector@@ -657,12 +660,6 @@     addPhiCtsNablas nablas (unitBag (PhiCoreCt x scr)) addCoreScrutTmCs _   _   _ = panic "addCoreScrutTmCs: numbers of scrutinees and match ids differ" --- | 'addCoreScrutTmCs', but desugars the 'LHsExpr's first.-addHsScrutTmCs :: [LHsExpr GhcTc] -> [Id] -> DsM a -> DsM a-addHsScrutTmCs scrs vars k = do-  scr_es <- traverse dsLExpr scrs-  addCoreScrutTmCs scr_es vars k- {- Note [Long-distance information] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider@@ -686,8 +683,8 @@ functions, which the call sites put into place with 'GHC.HsToCore.Monad.updPmNablas'. Call sites also extend this set with facts from type-constraint dictionaries,-case scrutinees, etc. with the exported functions 'addTyCs', 'addCoreScrutTmCs'-and 'addHsScrutTmCs'.+case scrutinees, etc. with the exported functions 'addTyCs' and+'addCoreScrutTmCs'.  Note [Recovering from unsatisfiable pattern-matching constraints] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
GHC/HsToCore/Pmc/Desugar.hs view
@@ -18,7 +18,8 @@  import GHC.HsToCore.Pmc.Types import GHC.HsToCore.Pmc.Utils-import GHC.Core (Expr(Var,App))+import GHC.Core (CoreExpr, Expr(Var,App))+import GHC.Core.Utils (stripTicksTopE) import GHC.Data.FastString (unpackFS, lengthFS) import GHC.Driver.DynFlags import GHC.Hs@@ -414,24 +415,28 @@ -- | Desugar a pattern guard --   @pat <- e ==>  let x = e;  <guards for pat <- x>@ desugarBind :: LPat GhcTc -> LHsExpr GhcTc -> DsM GrdDag-desugarBind p e = dsLExpr e >>= \case-  Var y-    | Nothing <- isDataConId_maybe y-    -- RHS is a variable, so that will allow us to omit the let-    -> desugarLPat y p-  rhs -> do-    (x, grds) <- desugarLPatV p-    pure (PmLet x rhs `consGrdDag` grds)+desugarBind p e =+  dsLExpr_stripTicks e >>= \case+    Var y+      | Nothing <- isDataConId_maybe y+      -- RHS is a variable, so that will allow us to omit the let+      -> desugarLPat y p+    rhs -> do+      (x, grds) <- desugarLPatV p+      pure (PmLet x rhs `consGrdDag` grds)  -- | Desugar a boolean guard --   @e ==>  let x = e; True <- x@ desugarBoolGuard :: LHsExpr GhcTc -> DsM GrdDag desugarBoolGuard e-  | isJust (isTrueLHsExpr e) = return GdEnd+  | isJust (isTrueLHsExpr e) -- NB: looks through ticks     -- The formal thing to do would be to generate (True <- True)     -- but it is trivial to solve so instead we give back an empty     -- GrdDag for efficiency-  | otherwise = dsLExpr e >>= \case+  = return GdEnd++  | otherwise+  = dsLExpr_stripTicks e >>= \case       Var y         | Nothing <- isDataConId_maybe y         -- Omit the let by matching on y@@ -439,6 +444,19 @@       rhs -> do         x <- mkPmId boolTy         pure $ sequencePmGrds [PmLet x rhs, vanillaConGrd x trueDataCon []]++-- | Desugar an expression, stripping off top-level ticks from the resulting+-- Core expression.+--+-- This function is used instead of 'dsLExpr' when we are immediately going to+-- inspect the Core (as we do in e.g. 'desugarBoolGuard' or 'desugarBind') to+-- make sure we properly look through intervening ticks (fixing #27360).+--+-- It's not needed when all we do is stash the resulting 'CoreExpr' into a+-- 'GrdDag', as the rest of the machinery (such as 'GHC.HsToCore.Pmc.Solver.addCoreCt')+-- looks through ticks.+dsLExpr_stripTicks :: LHsExpr GhcTc -> DsM CoreExpr+dsLExpr_stripTicks e = stripTicksTopE (const True) <$> dsLExpr e  {- Note [Field match order for RecCon] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
GHC/HsToCore/Pmc/Solver.hs view
@@ -642,11 +642,11 @@          -- return the new inert set and increment the sequence number n        ; return (TySt (n+1) <$> mb_new_inert) } --- | Allocates a fresh 'EvVar' name for 'PredTy's.+-- | Allocates a fresh 'EvVar' name for 'PredTy's nameTyCt :: PredType -> DsM EvVar nameTyCt pred_ty = do   unique <- getUniqueM-  let occname = mkVarOccFS (fsLit ("pm_"++show unique))+  let occname = mkVarOccFS $ fsLit "pm"   return (mkUserLocalOrCoVar occname unique ManyTy pred_ty noSrcSpan)  -----------------------------@@ -1000,8 +1000,9 @@       , let expr' = makeDictsCoherent expr ] makeDictsCoherent (Cast expr co)   = Cast (makeDictsCoherent expr) co-makeDictsCoherent (Tick tick expr)-  = Tick tick (makeDictsCoherent expr)+makeDictsCoherent (Tick _tick expr)+  -- See Wrinkle (UD1) in Note [Unique dictionaries in the TmOracle CoreMap]+  = makeDictsCoherent expr makeDictsCoherent ty@(Type {})   = ty makeDictsCoherent co@(Coercion {})@@ -1061,6 +1062,25 @@ checker was the most self-contained, although we might want to revisit once we implement a more robust approach to computing equality in the pattern-match checker (see #19272).++Wrinkle (UD1): ticks+--------------------+'makeDictsCoherent' also drops all ticks. The CoreMap key represents+value-level equality, which ticks never affect.++Example (#27314): with -finfo-table-map every record-selector use site is+wrapped in a 'SourceNote' carrying that site's span (see+Note [Record-selector ticks] in GHC.HsToCore.Ticks). Given++    data Box = Box { unBox :: Maybe Int }+    f b = case unBox b of+      Nothing -> 0+      Just _  -> let Just x = unBox b in x++the two `unBox b`s carry different SourceNote spans. Without tick stripping+the CoreMap treats them as distinct expressions. Long-distance information+from the outer `Just _` branch therefore never reaches the let-pattern, and+`Just x = unBox b` is wrongly reported as non-exhaustive. -}  {- Note [The Pos/Neg invariant]
GHC/HsToCore/Pmc/Solver/Types.hs view
@@ -626,6 +626,15 @@ coreExprAsPmLit (Tick _t e) = coreExprAsPmLit e coreExprAsPmLit (Lit l) = literalToPmLit (literalType l) l coreExprAsPmLit e = case collectArgs e of++  -- Look through nospec, noinline and lazy, which are only eliminated by Core Prep.+  -- See Note [coreExprAsPmLit and nospec]+  (Var x, Type _ : inner : rest_args)+    | x `hasKey` nospecIdKey+   || x `hasKey` noinlineIdKey+   || x `hasKey` lazyIdKey+    -> coreExprAsPmLit (mkApps inner rest_args)+   (Var x, [Lit l])     | Just dc <- isDataConWorkId_maybe x     , dc `elem` [intDataCon, wordDataCon, charDataCon, floatDataCon, doubleDataCon]@@ -768,6 +777,34 @@ Which is then passed to overloadPmLit which simply returns it as-is since it's already overloaded. +Note [coreExprAsPmLit and nospec]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+For coverage checking, we need to analyse overloaded literal patterns to figure+out which literals they correspond to; this is what 'coreExprAsPmLit' does.+For example, the literal pattern "fromString" (with -XOverloadedStrings)+will turn into an equality check against the **expression**++  fromString @T $dFromString "hello"#++and 'coreExprAsPmLit' recovers the string by taking apart this application.++However, when $dFromString is non-canonical (e.g. when an INCOHERENT+instance was discarded during resolution of the typeclass constraint, or when+the dictionary comes from 'withDict'), the desugarer wraps 'fromString' in+'nospec' (as per Note [nospecId magic] in GHC.Types.Id.Make and+Note [Desugaring non-canonical evidence] in GHC.HsToCore.Expr):++  nospec @(IsString a => String -> Maybe a) fromString @T $dFromString "hello"#++(For a full example, see test case T27124a.)++The 'nospec' mechanism only exists for the specialiser; it should be transparent+to everything else. 'coreExprAsPmLit' must thus look through the 'nospec'+application in order obtain the string "hello". If it doesn't, we can't do+pattern match checking (in fact GHC.HsToCore.Pmc.Desugar.desugarPat is liable+to crash!).++The same reasoning applies to `noinline` and `lazy`. -}  instance Outputable PmLitValue where
GHC/HsToCore/Quote.hs view
@@ -1189,11 +1189,11 @@ repRuleMatch FunLike = dataCon funLikeDataConName  repPhases :: Activation -> MetaM (Core TH.Phases)-repPhases (ActiveBefore _ i) = do { MkC arg <- coreIntLit i-                                  ; dataCon' beforePhaseDataConName [arg] }-repPhases (ActiveAfter _ i)  = do { MkC arg <- coreIntLit i-                                  ; dataCon' fromPhaseDataConName [arg] }-repPhases _                  = dataCon allPhasesDataConName+repPhases (ActiveBefore i) = do { MkC arg <- coreIntLit i+                                ; dataCon' beforePhaseDataConName [arg] }+repPhases (ActiveAfter i)  = do { MkC arg <- coreIntLit i+                                ; dataCon' fromPhaseDataConName [arg] }+repPhases _                = dataCon allPhasesDataConName  rep_complete_sig :: [LocatedN Name]                  -> Maybe (LocatedN Name)
GHC/HsToCore/Usage.hs view
@@ -73,6 +73,8 @@   { uc_safe_implicit_imps_req :: !Bool -- ^ Are all implicit imports required to be safe for this Safe Haskell mode?   } +-- | Build the list of 'Usage's that drive recompilation checking.+-- The resulting list is deterministically sorted. mkUsageInfo :: UsageConfig -> Plugins -> FinderCache -> UnitEnv             -> Module -> ImportedMods -> [ImportUserSpec] -> NameSet             -> [FilePath] -> [(Module, Fingerprint)] -> [Linkable] -> PkgsLoaded@@ -100,10 +102,10 @@                                     }                                | (mod, hash) <- merged ]                             ++ object_usages-    usages `seqList` return usages-    -- seq the list of Usages returned: occasionally these-    -- don't get evaluated for a while and we can end up hanging on to-    -- the entire collection of Ifaces.+    usages `seqList` return (sortBy stableUsageCmp usages)+    -- The use of 'seqList' is important because occasionally the returned list+    -- is not evaluated for a while, so that with too much laziness here we+    -- could end up hanging on to the entire collection of 'Iface's.  {- Note [Plugin dependencies] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
GHC/Iface/Errors.hs view
@@ -131,7 +131,7 @@                  | otherwise                 -> GenericMissing-                    (map ((\uid -> (uid, lookupUnit (ue_homeUnitState unit_env) uid))) pkg_hiddens)+                    pkg_hiddens                     mod_hiddens unusables files             _ -> panic "cantFindErr" 
GHC/Iface/Errors/Ppr.hs view
@@ -267,13 +267,13 @@                 .ppr.mkUnit) res ++       if f then [text "a package flag"] else []       )-    pkg_hidden :: (Unit, Maybe UnitInfo) -> SDoc-    pkg_hidden (uid, uif) =+    pkg_hidden :: UnitInfo -> SDoc+    pkg_hidden unit =         text "It is a member of the hidden package"-        <+> quotes (ppr uid)+        <+> quotes (ppr $ unitId unit)         --FIXME: we don't really want to show the unit id here we should         -- show the source package id or installed package id if it's ambiguous-        <> dot $$ maybe empty pkg_hidden_hint uif+        <> dot $$ pkg_hidden_hint unit       mod_hidden pkg =
GHC/Iface/Errors/Types.hs view
@@ -79,7 +79,7 @@   | NotAModule   | CouldntFindInFiles [FilePath]   | GenericMissing-      [(Unit, Maybe UnitInfo)] [Unit]+      [UnitInfo] [Unit]       [UnusableUnit] [FilePath]   | MultiplePackages [(Module, ModuleOrigin)]   deriving Generic
GHC/Iface/Load.hs view
@@ -62,6 +62,8 @@ import GHC.Iface.Env import GHC.Iface.Errors as Iface_Errors +import GHC.HsToCore.Breakpoints.Types (modBreaks_locs)+ import GHC.Tc.Errors.Types import GHC.Tc.Utils.Monad @@ -112,6 +114,7 @@ import GHC.Data.Maybe  import Control.Monad+import qualified Data.Foldable as Foldable import Data.Map ( toList ) import System.FilePath import System.Directory@@ -915,13 +918,13 @@               && not (isOneShot (ghcMode dflags))             then return (Failed (HomeModError mod loc))             else do-                r <- read_file hooks logger name_cache unit_state dflags wanted_mod (ml_hi_file loc)+                r <- read_file hooks logger name_cache dflags wanted_mod (ml_hi_file loc)                 case r of                   Failed err                     -> return (Failed $ BadIfaceFile err)                   Succeeded (iface,_fp)                     -> do-                        r2 <- load_dynamic_too_maybe hooks logger name_cache unit_state+                        r2 <- load_dynamic_too_maybe hooks logger name_cache                                                  (setDynamicNow dflags) wanted_mod                                                  iface loc                         case r2 of@@ -937,20 +940,20 @@                               err  -- | Check if we need to try the dynamic interface for -dynamic-too-load_dynamic_too_maybe :: Hooks -> Logger -> NameCache -> UnitState -> DynFlags+load_dynamic_too_maybe :: Hooks -> Logger -> NameCache -> DynFlags                        -> Module -> ModIface -> ModLocation                        -> IO (MaybeErr MissingInterfaceError ())-load_dynamic_too_maybe hooks logger name_cache unit_state dflags wanted_mod iface loc+load_dynamic_too_maybe hooks logger name_cache dflags wanted_mod iface loc   -- Indefinite interfaces are ALWAYS non-dynamic.   | not (moduleIsDefinite (mi_module iface)) = return (Succeeded ())-  | gopt Opt_BuildDynamicToo dflags = load_dynamic_too hooks logger name_cache unit_state dflags wanted_mod iface loc+  | gopt Opt_BuildDynamicToo dflags = load_dynamic_too hooks logger name_cache dflags wanted_mod iface loc   | otherwise = return (Succeeded ()) -load_dynamic_too :: Hooks -> Logger -> NameCache -> UnitState -> DynFlags+load_dynamic_too :: Hooks -> Logger -> NameCache -> DynFlags                  -> Module -> ModIface -> ModLocation                  -> IO (MaybeErr MissingInterfaceError ())-load_dynamic_too hooks logger name_cache unit_state dflags wanted_mod iface loc = do-  read_file hooks logger name_cache unit_state dflags wanted_mod (ml_dyn_hi_file loc) >>= \case+load_dynamic_too hooks logger name_cache dflags wanted_mod iface loc = do+  read_file hooks logger name_cache dflags wanted_mod (ml_dyn_hi_file loc) >>= \case     Succeeded (dynIface, _)      | mi_mod_hash iface == mi_mod_hash dynIface      -> return (Succeeded ())@@ -964,10 +967,10 @@   -read_file :: Hooks -> Logger -> NameCache -> UnitState -> DynFlags+read_file :: Hooks -> Logger -> NameCache -> DynFlags           -> Module -> FilePath           -> IO (MaybeErr ReadInterfaceError (ModIface, FilePath))-read_file hooks logger name_cache unit_state dflags wanted_mod file_path = do+read_file hooks logger name_cache dflags wanted_mod file_path = do    -- Figure out what is recorded in mi_module.  If this is   -- a fully definite interface, it'll match exactly, but@@ -976,7 +979,7 @@         case getModuleInstantiation wanted_mod of             (_, Nothing) -> wanted_mod             (_, Just indef_mod) ->-              instModuleToModule unit_state+              instModuleToModule                 (uninstantiateInstantiatedModule indef_mod)   read_result <- readIface hooks logger dflags name_cache wanted_mod' file_path   case read_result of@@ -1159,9 +1162,11 @@         , vcat [ppr ver $$ nest 2 (ppr decl) | (ver,decl) <- mi_decls iface]         , case mi_simplified_core iface of             Nothing -> empty-            Just (IfaceSimplifiedCore eds fs) ->+            Just (IfaceSimplifiedCore eds mbs fs) ->               vcat [ text "extra decls:"                            $$ nest 2 (vcat ([ppr bs | bs <- eds]))+                   , text "mod breaks:"+                           $$ nest 2 (ppr $ Foldable.toList . modBreaks_locs <$> mbs)                    , text "foreign stubs:"                            $$ nest 2 (ppr fs)                    ]
GHC/Iface/Make.hs view
@@ -34,6 +34,7 @@ import GHC.Iface.Recomp import GHC.Iface.Load import GHC.Iface.Ext.Fields+import GHC.HsToCore.Breakpoints.Types (ModBreaks)  import GHC.CoreToIface @@ -122,11 +123,12 @@          , mg_safe_haskell = safe_mode          , mg_trust_pkg    = self_trust          , mg_docs         = docs+         , mg_modBreaks    = modBreaks          }   = do       self_recomp <- traverse (mkSelfRecomp hsc_env this_mod (ms_hs_hash mod_summary)) usages       return $ mkIface_ hsc_env this_mod core_prog hsc_src deps rdr_env import_decls fix_env warns self_trust-                safe_mode self_recomp docs mod_details+                safe_mode self_recomp docs mod_details modBreaks  -- | Fully instantiate an interface. Adds fingerprints and potentially code -- generator produced information.@@ -228,9 +230,10 @@           -> ModDetails         -- gotten from mkBootModDetails, probably           -> ModSummary           -> Maybe CoreProgram+          -> Maybe ModBreaks           -> TcGblEnv           -- Usages, deprecations, etc           -> IO ModIface-mkIfaceTc hsc_env safe_mode mod_details mod_summary mb_program+mkIfaceTc hsc_env safe_mode mod_details mod_summary mb_program mb_modBreaks   tc_result@TcGblEnv{ tcg_mod = this_mod,                       tcg_src = hsc_src,                       tcg_imports = imports,@@ -258,6 +261,7 @@                    (imp_trust_own_pkg imports) safe_mode self_recomp                    docs                    mod_details+                   mb_modBreaks            mkFullIface hsc_env partial_iface Nothing Nothing NoStubs [] @@ -302,6 +306,7 @@          -> Maybe IfaceSelfRecomp          -> Maybe Docs          -> ModDetails+         -> Maybe ModBreaks          -> PartialModIface mkIface_ hsc_env          this_mod core_prog hsc_src deps rdr_env import_decls fix_env src_warns@@ -319,15 +324,17 @@ --      only at the TypeEnv.  The previous Tidy phase has --      put exactly the info into the TypeEnv that we want --      to expose in the interface-+        modBreaks   = do     let home_unit    = hsc_home_unit hsc_env         semantic_mod = homeModuleNameInstantiation home_unit (moduleName this_mod)         entities = typeEnvElts type_env         show_linear_types = xopt LangExt.LinearTypes (hsc_dflags hsc_env) -        simplified_core = if gopt Opt_WriteIfSimplifiedCore dflags then Just (IfaceSimplifiedCore [ toIfaceTopBind b | b <- core_prog ] emptyIfaceForeign)-                                                                   else Nothing+        simplified_core =+          if gopt Opt_WriteIfSimplifiedCore dflags+          then Just (IfaceSimplifiedCore [ toIfaceTopBind b | b <- core_prog ] modBreaks emptyIfaceForeign)+          else Nothing         decls  = [ tyThingToIfaceDecl show_linear_types entity                  | entity <- entities,                    let name = getName entity,
GHC/Iface/Recomp.hs view
@@ -617,7 +617,7 @@         new_merged = case lookupUniqMap (requirementContext unit_state)                           (ms_mod_name mod_summary) of                         Nothing -> []-                        Just r -> sort $ map (instModuleToModule unit_state) r+                        Just r -> sort $ map instModuleToModule r     if old_merged == new_merged         then up_to_date logger (text "signatures to merge in unchanged" $$ ppr new_merged)         else return $ needsRecompileBecause SigsMergeChanged@@ -1208,7 +1208,7 @@        sorted_extra_decls :: Maybe IfaceSimplifiedCore       sorted_extra_decls = mi_simplified_core iface0 <&> \simpl_core ->-         IfaceSimplifiedCore (sortOn binding_key (mi_sc_extra_decls simpl_core)) (mi_sc_foreign simpl_core)+         IfaceSimplifiedCore (sortOn binding_key (mi_sc_extra_decls simpl_core)) (mi_sc_modBreaks simpl_core) (mi_sc_foreign simpl_core)    -- The interface hash depends on:   --   - the ABI hash, plus@@ -1767,10 +1767,12 @@       IfaceClass{ifBody = IfConcreteClass { ifSigs=sigs, ifATs=ats }} ->                      IfaceClassExtras (fix_fn n) insts (ann_fn (AnnOccName n)) meths defms           where-            insts = (map ifDFun $ (concatMap at_extras ats)-                                    ++ lookupOccEnvL inst_env n)-                           -- Include instances of the associated types-                           -- as well as instances of the class (#5147)+            insts =+              let (atFamInsts, atClsInsts) = foldMap at_extras ats+              in (ifFamInstAxiom <$> atFamInsts) ++ (ifDFun <$> atClsInsts)+                 ++ (ifDFun <$> lookupOccEnvL inst_env n)+                           -- Include instances and axioms of the associated types+                           -- as well as instances of the class (#5147) (#26183)             meths = [id_extras (getOccName op) | IfaceClassOp op _ _ <- sigs]             -- Names of all the default methods (see Note [default method Name])             defms = [ dmName@@ -1780,14 +1782,19 @@       IfaceSynonym{} -> IfaceSynonymExtras (fix_fn n)                                            (ann_fn (AnnOccName n))       IfaceFamily{} -> IfaceFamilyExtras (fix_fn n)-                        (map ifFamInstAxiom (lookupOccEnvL fi_env n))+                        (map ifFamInstAxiom (lookupOccEnvL fi_env n)+                        ++ map ifDFun (lookupOccEnvL inst_env n)+                        )                         (ann_fn (AnnOccName n))       IfacePatSyn{} -> IfacePatSynExtras (fix_fn n) (lookup_complete_match n)       _other -> IfaceOtherDeclExtras   where         n = getOccName decl         id_extras occ = IdExtras (fix_fn occ) (lookupOccEnvL rule_env occ) (ann_fn (AnnOccName occ)) (lookup_complete_match occ)-        at_extras (IfaceAT decl _) = lookupOccEnvL inst_env (getOccName decl)+        at_extras (IfaceAT decl _) =+          ( lookupOccEnvL fi_env (getOccName decl) -- Axioms+          , lookupOccEnvL inst_env (getOccName decl) -- Class instances+          )          lookup_complete_match occ = lookupOccEnvL complete_env occ 
GHC/Iface/Type.hs view
@@ -7,7 +7,7 @@ -}  -{-# LANGUAGE MultiWayIf #-}+{-# LANGUAGE MultiWayIf, OverloadedRecordDot #-} {-# LANGUAGE LambdaCase #-} module GHC.Iface.Type (         IfExtName,@@ -1742,6 +1742,7 @@     sdocOption sdocPrintExplicitKinds $ \print_kinds ->     sdocOption sdocPrintTypeAbbreviations $ \print_type_abbreviations ->     getPprDebug $ \debug ->+    getPprStyle $ \style ->      if | ifaceTyConName tc `hasKey` ipClassKey        , IA_Arg (IfaceLitTy (IfaceStrTyLit n))@@ -1793,6 +1794,14 @@        | Just doc <- ppr_equality ctxt_prec tc (appArgsIfaceTypes tys)        -> doc +       -- See Note [The types Any and UnusedType], specifically (Any6) and (Any7)+       | ifaceTyConName tc `hasKey` unusedTypeTyConKey+       , ((arg_k, _) : (IfaceLitTy (IfaceStrTyLit arg_nm), _) : args_usr)+         <- appArgsIfaceTypesForAllTyFlags tys+         -- if arg_k is a kind with more than 0 arguments, then _ might not be [] here+       , userStyle style+       -> ppr_iface_unused_ty_tycon ctxt_prec arg_k arg_nm args_usr+        | otherwise        -> ppr_iface_tc_app ppr_app_arg ctxt_prec tc $           appArgsIfaceTypesForAllTyFlags $ stripInvisArgs (PrintExplicitKinds print_kinds) tys@@ -1805,6 +1814,23 @@    True  -> maybeParen ctxt_prec starPrec $               unicodeSyntax (char '★') (char '*') +-- | user-style printer that pretty-prints an 'UnusedType @k "foo_3" to foo_3.+-- If -fprint-explicit-kinds or -fprint-explicit-runtime-reps are set, instead+-- prints them to (foo3 :: k).+-- See Note [The types Any and UnusedType], specifically (Any6) and (Any7) for why this is useful.+ppr_iface_unused_ty_tycon :: PprPrec -> IfaceType -> LexicalFastString -> [(IfaceType, ForAllTyFlag)] -> SDoc+ppr_iface_unused_ty_tycon ctxt_prec arg_k arg_nm args_usr+  = sdocOption sdocPrintExplicitKinds       $ \print_kinds ->+    sdocOption sdocPrintExplicitRuntimeReps $ \print_reps  ->+      if print_kinds || print_reps+      then prettyMeta $ \nm ->+             maybeParen sig_prec sigPrec $ nm <+> text "::" <+> pprIfaceType arg_k+      else prettyMeta id+  where sig_prec = if null args_usr then ctxt_prec else appPrec+        prettyMeta add_ty+          = pprIfacePrefixApp ctxt_prec (add_ty $ ppr arg_nm)+          $ map (ppr_app_arg appPrec) args_usr+ -- | Pretty-print a type-level equality. -- Returns (Just doc) if the argument is a /saturated/ application -- of   eqTyCon          (~)@@ -2191,7 +2217,8 @@          0 -> return IfaceNormalTyCon          1 -> IfaceTupleTyCon <$> get bh <*> get bh          2 -> IfaceSumTyCon <$> get bh-         _ -> return IfaceEqualityTyCon+         3 -> return IfaceEqualityTyCon+         _ -> panic "get IfaceTyConSort"  instance Binary IfaceTyConInfo where    put_ bh (IfaceTyConInfo i s) = put_ bh i >> put_ bh s
GHC/IfaceToCore.hs view
@@ -75,7 +75,6 @@ import GHC.Core.Lint import GHC.Core.Make import GHC.Core.Class-import GHC.Core.Predicate( isUnaryClass ) import GHC.Core.TyCon import GHC.Core.ConLike import GHC.Core.DataCon@@ -1788,7 +1787,7 @@ tcIdDetails :: Name -> Type -> IfaceIdDetails -> IfL IdDetails tcIdDetails _ _  IfVanillaId           = return VanillaId tcIdDetails _ _  (IfWorkerLikeId dmds) = return $ WorkerLikeId dmds-tcIdDetails _ ty IfDFunId              = return (DFunId (isUnaryClass cls))+tcIdDetails _ ty IfDFunId              = return (mkDFunIdDetails cls)   where     (_, _, cls, _) = tcSplitDFunTy ty 
GHC/Linker/Loader.hs view
@@ -377,7 +377,7 @@       let hsc' = hscSetActiveUnitId uid hsc_env       -- Load potential dependencies first       (done', pls') <- foldM (\(done', pls') uid -> load done' uid pls') (done, pls)-                          (homeUnitDepends (hsc_units hsc'))+                          (Set.toList (homeUnitDepends (hsc_units hsc')))       pls'' <- loadCmdLineLibs'' interp hsc' pls'       return $ (Set.insert uid done', pls'') 
GHC/Linker/Static.hs view
@@ -241,7 +241,19 @@                           then ["-Wl,--gc-sections"]                           else []) +                      -- On Windows, module .o files may be archives (see+                      -- Note [Object merging] in GHC.Driver.Pipeline.Execute).+                      -- Use --whole-archive to ensure all archive members are+                      -- included, especially those containing .ctors/.dtors+                      -- initializer/finalizer sections. See Note [Initializers and+                      -- finalizers in Cmm] in GHC.Cmm.InitFini.+                      ++ (if platformOS platform == OSMinGW32+                          then ["-Wl,--whole-archive"]+                          else [])                       ++ o_files+                      ++ (if platformOS platform == OSMinGW32+                          then ["-Wl,--no-whole-archive"]+                          else [])                       ++ lib_path_opts)                       ++ extra_ld_inputs                       ++ map GHC.SysTools.Option (
GHC/Linker/Types.hs view
@@ -47,6 +47,7 @@    , linkableFilterByteCode    , linkableFilterNative    , partitionLinkables+   , linkableAllBCOs    ) where @@ -351,6 +352,17 @@ -- This excludes the LazyBCOs and the CoreBindings parts linkableBCOs :: Linkable -> [CompiledByteCode] linkableBCOs l = [ cbc | BCOs cbc <- NE.toList (linkableParts l) ]++linkableAllBCOs :: Linkable -> [CompiledByteCode]+linkableAllBCOs l = mapMaybe bcos $ NE.toList (linkableParts l)+  where+    -- Note: explicit match on all constructors to trigger warning when new ones are introduced.+    bcos (BCOs bco) = Just bco+    bcos (LazyBCOs bco _fs) = Just bco -- TODO: _fs ?+    bcos DotA{} = Nothing+    bcos DotDLL{} = Nothing+    bcos CoreBindings{} = Nothing+    bcos DotO{} = Nothing  -- | List the native linkable parts (.o/.so/.dll) of a linkable linkableNativeParts :: Linkable -> [LinkablePart]
GHC/Parser.hs view
@@ -6810,8 +6810,8 @@ 	case happyOutTok happy_x_2 of { happy_var_2 ->  	case happyOutTok happy_x_3 of { happy_var_3 ->  	happyIn142-		 (( ActivationAnn (epTok happy_var_1) (epTok happy_var_3) Nothing (Just (glR happy_var_2))-                                  , ActiveAfter  (getINTEGERs happy_var_2) (fromInteger (il_value (getINTEGER happy_var_2))))+		 (( ActivationAnn (epTok happy_var_1) (getINTEGERs happy_var_2) (epTok happy_var_3) Nothing (Just (glR happy_var_2))+                                  , ActiveAfter  (fromInteger (il_value (getINTEGER happy_var_2)))) 	)}}}  happyReduce_318 :: () => Happy_GHC_Exts.Int# -> (Located Token) -> Happy_GHC_Exts.Int# -> Happy_IntList -> HappyStk (HappyAbsSyn ) -> P (HappyAbsSyn )@@ -6826,8 +6826,8 @@ 	case happyOutTok happy_x_3 of { happy_var_3 ->  	case happyOutTok happy_x_4 of { happy_var_4 ->  	happyIn142-		 (( ActivationAnn (epTok happy_var_1) (epTok happy_var_4) happy_var_2 (Just (glR happy_var_3))-                                  , ActiveBefore (getINTEGERs happy_var_3) (fromInteger (il_value (getINTEGER happy_var_3))))+		 (( ActivationAnn (epTok happy_var_1) (getINTEGERs happy_var_3) (epTok happy_var_4) happy_var_2 (Just (glR happy_var_3))+                                  , ActiveBefore (fromInteger (il_value (getINTEGER happy_var_3)))) 	) `HappyStk` happyRest}}}}  happyReduce_319 :: () => Happy_GHC_Exts.Int# -> (Located Token) -> Happy_GHC_Exts.Int# -> Happy_IntList -> HappyStk (HappyAbsSyn ) -> P (HappyAbsSyn )@@ -6839,8 +6839,8 @@ 	case happyOut141 happy_x_2 of { (HappyWrap141 happy_var_2) ->  	case happyOutTok happy_x_3 of { happy_var_3 ->  	happyIn142-		 (( ActivationAnn (epTok happy_var_1) (epTok happy_var_3) happy_var_2 Nothing-                                  , NeverActive)+		 (( ActivationAnn (epTok happy_var_1) NoSourceText (epTok happy_var_3) happy_var_2 Nothing+                                  , NeverActive ) 	)}}}  happyReduce_320 :: () => Happy_GHC_Exts.Int# -> (Located Token) -> Happy_GHC_Exts.Int# -> Happy_IntList -> HappyStk (HappyAbsSyn ) -> P (HappyAbsSyn )@@ -9202,8 +9202,8 @@ 	case happyOutTok happy_x_2 of { happy_var_2 ->  	case happyOutTok happy_x_3 of { happy_var_3 ->  	happyIn219-		 ((ActivationAnn (epTok happy_var_1) (epTok  happy_var_3) Nothing (Just (glR happy_var_2))-                                  ,ActiveAfter  (getINTEGERs happy_var_2) (fromInteger (il_value (getINTEGER happy_var_2))))+		 ((ActivationAnn (epTok happy_var_1) (getINTEGERs happy_var_2) (epTok  happy_var_3) Nothing (Just (glR happy_var_2))+                                  ,ActiveAfter   (fromInteger (il_value (getINTEGER happy_var_2)))) 	)}}}  happyReduce_528 :: () => Happy_GHC_Exts.Int# -> (Located Token) -> Happy_GHC_Exts.Int# -> Happy_IntList -> HappyStk (HappyAbsSyn ) -> P (HappyAbsSyn )@@ -9218,8 +9218,8 @@ 	case happyOutTok happy_x_3 of { happy_var_3 ->  	case happyOutTok happy_x_4 of { happy_var_4 ->  	happyIn219-		 ((ActivationAnn (epTok happy_var_1) (epTok happy_var_4) happy_var_2 (Just (glR happy_var_3))-                                  ,ActiveBefore (getINTEGERs happy_var_3) (fromInteger (il_value (getINTEGER happy_var_3))))+		 ((ActivationAnn (epTok happy_var_1) (getINTEGERs happy_var_3) (epTok happy_var_4) happy_var_2 (Just (glR happy_var_3))+                                  ,ActiveBefore  (fromInteger (il_value (getINTEGER happy_var_3)))) 	) `HappyStk` happyRest}}}}  happyReduce_529 :: () => Happy_GHC_Exts.Int# -> (Located Token) -> Happy_GHC_Exts.Int# -> Happy_IntList -> HappyStk (HappyAbsSyn ) -> P (HappyAbsSyn )
GHC/Parser/HaddockLex.hs view
@@ -1,7 +1,7 @@ {-# OPTIONS_GHC -fno-warn-unused-binds -fno-warn-missing-signatures #-} {-# LANGUAGE CPP #-} {-# LANGUAGE MagicHash #-}-{-# LINE 1 "_build/source-dist/ghc-9.14.1-src/ghc-9.14.1/compiler/GHC/Parser/HaddockLex.x" #-}+{-# LINE 1 "_build/source-dist/ghc-9.14.2-src/ghc-9.14.2/compiler/GHC/Parser/HaddockLex.x" #-} {-# OPTIONS_GHC -funbox-strict-fields #-}  module GHC.Parser.HaddockLex (lexHsDoc, lexStringLiteral) where@@ -353,7 +353,7 @@         -- match when checking the right context, just         -- the first match will do. #endif-{-# LINE 85 "_build/source-dist/ghc-9.14.1-src/ghc-9.14.1/compiler/GHC/Parser/HaddockLex.x" #-}+{-# LINE 85 "_build/source-dist/ghc-9.14.2-src/ghc-9.14.2/compiler/GHC/Parser/HaddockLex.x" #-} data AlexInput = AlexInput   { alexInput_position     :: !RealSrcLoc   , alexInput_string       :: !ByteString
GHC/Parser/Lexer.hs view
@@ -1,7 +1,7 @@ {-# OPTIONS_GHC -fno-warn-unused-binds -fno-warn-missing-signatures #-} {-# LANGUAGE CPP #-} {-# LANGUAGE MagicHash #-}-{-# LINE 43 "_build/source-dist/ghc-9.14.1-src/ghc-9.14.1/compiler/GHC/Parser/Lexer.x" #-}+{-# LINE 43 "_build/source-dist/ghc-9.14.2-src/ghc-9.14.2/compiler/GHC/Parser/Lexer.x" #-} {-# LANGUAGE CPP #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE LambdaCase #-}@@ -1118,7 +1118,7 @@         -- match when checking the right context, just         -- the first match will do. #endif-{-# LINE 762 "_build/source-dist/ghc-9.14.1-src/ghc-9.14.1/compiler/GHC/Parser/Lexer.x" #-}+{-# LINE 762 "_build/source-dist/ghc-9.14.2-src/ghc-9.14.2/compiler/GHC/Parser/Lexer.x" #-} -- Operator whitespace occurrence. See Note [Whitespace-sensitive operator parsing]. data OpWs   = OpWsPrefix         -- a !b
GHC/Parser/Lexer/String.hs view
@@ -1,7 +1,7 @@ {-# OPTIONS_GHC -fno-warn-unused-binds -fno-warn-missing-signatures #-} {-# LANGUAGE CPP #-} {-# LANGUAGE MagicHash #-}-{-# LINE 1 "_build/source-dist/ghc-9.14.1-src/ghc-9.14.1/compiler/GHC/Parser/Lexer/String.x" #-}+{-# LINE 1 "_build/source-dist/ghc-9.14.2-src/ghc-9.14.2/compiler/GHC/Parser/Lexer/String.x" #-} {- | This module defines lex states for strings. @@ -346,7 +346,7 @@         -- match when checking the right context, just         -- the first match will do. #endif-{-# LINE 91 "_build/source-dist/ghc-9.14.1-src/ghc-9.14.1/compiler/GHC/Parser/Lexer/String.x" #-}+{-# LINE 91 "_build/source-dist/ghc-9.14.2-src/ghc-9.14.2/compiler/GHC/Parser/Lexer/String.x" #-} -- | Dummy action that should never be called. Should only be used in lex states -- that are manually lexed in tok_string_multi. string_multi_content_action :: a
GHC/Platform/Ways.hs view
@@ -154,6 +154,14 @@     -- .so before loading the .so using the system linker.  Since only     -- PIC objects can be linked into a .so, we have to compile even     -- modules of the main program with -fPIC when using -dynamic.+wayGeneralFlags platform WayProf+    | ArchAArch64 <- platformArch platform+    , OSLinux <- platformOS platform = [Opt_InterModuleFarJumps]+    {- note(mangoiv):+     - on aarch64 profiled-dynamic, we are seeing jump offset overflow+     - errors on certain binutils versions. This can probably be deactivated+     - if we stop supporting binutils 2.44 / GCC 14.2+     - https://gitlab.haskell.org/ghc/ghc/-/issues/26994 -} wayGeneralFlags _ WayProf     = []  -- | Turn these flags off when enabling this way
GHC/Rename/Env.hs view
@@ -16,9 +16,9 @@          lookupLocatedTopBndrRnN, lookupTopBndrRn, -        lookupLocatedOccRn, lookupLocatedOccRnConstr, lookupLocatedOccRnRecField,+        lookupLocatedOccRn, lookupLocatedOccRnGRE, lookupLocatedOccRnConstr, lookupLocatedOccRnRecField,         lookupLocatedOccRnNone,-        lookupOccRn, lookupOccRn_maybe, lookupSameOccRn_maybe,+        lookupOccRn, lookupOccRnGRE, lookupOccRn_maybe, lookupSameOccRn_maybe,         lookupLocalOccRn_maybe, lookupInfoOccRn,         lookupLocalOccThLvl_maybe, lookupLocalOccRn,         lookupTypeOccRn,@@ -997,6 +997,11 @@                    -> TcRn (GenLocated (EpAnn ann) Name) lookupLocatedOccRn what = wrapLocMA (lookupOccRn what) +lookupLocatedOccRnGRE :: WhatLooking+                      -> GenLocated (EpAnn ann) RdrName+                      -> TcRn (GenLocated (EpAnn ann) GlobalRdrElt)+lookupLocatedOccRnGRE what = wrapLocMA (lookupOccRnGRE what)+ lookupLocatedOccRnConstr :: GenLocated (EpAnn ann) RdrName                          -> TcRn (GenLocated (EpAnn ann) Name) lookupLocatedOccRnConstr = wrapLocMA lookupOccRnConstr@@ -1024,11 +1029,14 @@ -- | lookupOccRn looks up an occurrence of a RdrName, and uses its argument to -- determine what kind of suggestions should be displayed if it is not in scope lookupOccRn :: WhatLooking -> RdrName -> RnM Name-lookupOccRn which_suggest rdr_name+lookupOccRn which_suggest = fmap greName . lookupOccRnGRE which_suggest++lookupOccRnGRE :: WhatLooking -> RdrName -> RnM GlobalRdrElt+lookupOccRnGRE which_suggest rdr_name   = do { mb_gre <- lookupOccRn_maybe rdr_name        ; case mb_gre of-           Just gre  -> return $ greName gre-           Nothing   -> reportUnboundName which_suggest rdr_name }+           Just gre  -> return gre+           Nothing   -> mkUnboundGRERdr rdr_name <$ reportUnboundName which_suggest rdr_name }  -- | Look up an occurrence of a 'RdrName'. --@@ -1092,16 +1100,20 @@  -- lookupTypeOccRn looks up an optionally promoted RdrName. -- Used for looking up type variables.-lookupTypeOccRn :: RdrName -> RnM Name+lookupTypeOccRn :: RdrName -> RnM GlobalRdrElt -- see Note [Demotion] lookupTypeOccRn rdr_name   = do { mb_gre <- lookupOccRn_maybe rdr_name        ; case mb_gre of-             Just gre -> return $ greName gre-             Nothing   ->-               if occName rdr_name == occName eqTyCon_RDR -- See Note [eqTyCon (~) compatibility fallback]-               then eqTyConName <$ addDiagnostic TcRnTypeEqualityOutOfScope-               else lookup_demoted rdr_name }+             Just gre -> return gre+             Nothing+               | occName rdr_name == occName eqTyCon_RDR -- See Note [eqTyCon (~) compatibility fallback]+                 -> do { addDiagnostic TcRnTypeEqualityOutOfScope+                       ; pure $+                          mkExactGRE eqTyConName $+                          IAmTyCon $+                          eqTyConName <$ tyConFlavour eqTyCon }+               | otherwise -> lookup_demoted rdr_name }  {- Note [eqTyCon (~) compatibility fallback] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~@@ -1118,7 +1130,7 @@ -}  -- Used when looking up a term name (varName or dataName) in a type-lookup_demoted :: RdrName -> RnM Name+lookup_demoted :: RdrName -> RnM GlobalRdrElt lookup_demoted rdr_name   | Just demoted_rdr <- demoteRdrNameTcCls rdr_name     -- Maybe it's the name of a *data* constructor@@ -1126,11 +1138,12 @@        ; star_is_type <- xoptM LangExt.StarIsType        ; let is_star_type = if star_is_type then StarIsType else StarIsNotType              star_is_type_hints = noStarIsTypeHints is_star_type rdr_name+             mk_unbound_name_GRE hint = unboundGREX looking_for rdr_name hint        ; if data_kinds             then do { mb_demoted_gre <- lookupOccRn_maybe demoted_rdr                     ; case mb_demoted_gre of-                        Nothing -> unboundNameX looking_for rdr_name star_is_type_hints-                        Just demoted_gre -> return $ greName demoted_gre}+                        Nothing -> mk_unbound_name_GRE star_is_type_hints+                        Just demoted_gre -> return demoted_gre}             else do { -- We need to check if a data constructor of this name is                       -- in scope to give good error messages. However, we do                       -- not want to give an additional error if the data@@ -1142,13 +1155,13 @@                                      = [SuggestExtension $ SuggestSingleExtension additional LangExt.DataKinds]                                      | otherwise                                      = star_is_type_hints-                    ; unboundNameX looking_for rdr_name suggestion } }+                    ; mk_unbound_name_GRE suggestion } }    | isQual rdr_name,     Just demoted_rdr_name <- demoteRdrNameTv rdr_name     -- Definitely an illegal term variable, as type variables are never exported.     -- See Note [Demotion of unqualified variables] (W2)-  = report_qualified_term_in_types rdr_name demoted_rdr_name+  = mkUnboundGREName <$> report_qualified_term_in_types rdr_name demoted_rdr_name    | isUnqual rdr_name,     Just demoted_rdr_name <- demoteRdrNameTv rdr_name@@ -1157,12 +1170,12 @@        ; if required_type_arguments          then do { mb_demoted_gre <- lookupOccRn_maybe demoted_rdr_name                  ; case mb_demoted_gre of-                     Nothing -> unboundName (LF WL_Anything WL_Anywhere) rdr_name-                     Just demoted_gre -> return $ greName demoted_gre }-         else unboundName looking_for rdr_name }+                     Nothing -> unboundGRE (LF WL_Anything WL_Anywhere) rdr_name+                     Just demoted_gre -> return demoted_gre }+         else unboundGRE looking_for rdr_name }    | otherwise-  = unboundName looking_for rdr_name+  = unboundGRE looking_for rdr_name    where     looking_for = LF WL_Type WL_Anywhere
GHC/Rename/Expr.hs view
@@ -328,7 +328,7 @@             -- matching GRE and add a name clash error             -- (see lookupGlobalOccRn_overloaded, called by lookupExprOccRn).             -> do { let sel_name = flSelector $ recFieldLabel fld_info-                  ; checkThLocalNameNoLift (L (l2l l) (WithUserRdr v sel_name))+                  ; checkThLocalNameNoLift (L l $ WithUserRdr v gre)                   ; return (XExpr (HsRecSelRn (FieldOcc v  (L l sel_name))), unitFV sel_name)                   }             | nm == nilDataConName@@ -339,7 +339,7 @@             -> rnExpr (ExplicitList noAnn [])              | otherwise-            -> do { res_expr <- checkThLocalNameWithLift (L (l2l l) (WithUserRdr v nm))+            -> do { res_expr <- checkThLocalNameWithLift (L (l2l l) (WithUserRdr v gre))                   ; return (res_expr, unitFV nm) }         }}} @@ -646,23 +646,27 @@ -}  rnExpr e@(HsStatic _ expr) = do-    -- Normally, you wouldn't be able to construct a static expression without-    -- first enabling -XStaticPointers in the first place, since that extension-    -- is what makes the parser treat `static` as a keyword. But this is not a-    -- sufficient safeguard, as one can construct static expressions by another-    -- mechanism: Template Haskell (see #14204). To ensure that GHC is-    -- absolutely prepared to cope with static forms, we check for-    -- -XStaticPointers here as well.-    unlessXOptM LangExt.StaticPointers $-      addErr $ TcRnIllegalStaticExpression e-    (expr',fvExpr) <- rnLExpr expr-    level <- getThLevel-    case level of-      Splice _ _ -> addErr $ TcRnTHError $ IllegalStaticFormInSplice e-      _        -> return ()-    mod <- getModule-    let fvExpr' = filterNameSet (nameIsLocalOrFrom mod) fvExpr-    return (HsStatic fvExpr' expr', fvExpr)+  do {  -- Normally, you wouldn't be able to construct a static expression without+        -- first enabling -XStaticPointers in the first place, since that extension+        -- is what makes the parser treat `static` as a keyword. But this is not a+        -- sufficient safeguard, as one can construct static expressions by another+        -- mechanism: Template Haskell (see #14204). To ensure that GHC is+        -- absolutely prepared to cope with static forms, we check for+        -- -XStaticPointers here as well.+     ; unlessXOptM LangExt.StaticPointers $+       addErr $ TcRnIllegalStaticExpression e++     ; (expr',fvExpr) <- rnLExpr expr++     -- Complain about staging+     ; level <- getThLevel+     ; case level of+        Splice _ _ -> addErr $ TcRnTHError $ IllegalStaticFormInSplice e+        _        -> return ()++     ; mod <- getModule+     ; let fvExpr' = filterNameSet (nameIsLocalOrFrom mod) fvExpr+     ; return (HsStatic fvExpr' expr', fvExpr) }  {- ************************************************************************
GHC/Rename/HsType.hs view
@@ -4,6 +4,7 @@ {-# LANGUAGE LambdaCase          #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies        #-}+{-# LANGUAGE MultiWayIf          #-}  {- (c) The GRASP/AQUA Project, Glasgow University, 1992-1998@@ -47,7 +48,7 @@  import GHC.Prelude -import {-# SOURCE #-} GHC.Rename.Splice( rnSpliceType, checkThLocalTyName )+import {-# SOURCE #-} GHC.Rename.Splice( rnSpliceType, checkThLocalTyName, checkThLocalNameNoLift )  import GHC.Core.TyCo.FVs ( tyCoVarsOfTypeList ) import GHC.Core.TyCon    ( isKindName )@@ -543,10 +544,19 @@          TcRnUnexpectedKindVar rdr_name            -- Any type variable at the kind level is illegal without the use            -- of PolyKinds (see #14710)-       ; name <- rnTyVar env rdr_name+       ; gre <- rnTyVar env rdr_name        ; this_mod <- getModule-       ; when (nameIsLocalOrFrom this_mod name) $-         checkThLocalTyName name+       ; explicit_level_imports <- xoptM LangExt.ExplicitLevelImports+       ; let loc_gre_with_rdr = L loc $ WithUserRdr rdr_name gre+             name = greName gre+       ; if  | explicit_level_imports+             -- See Note [Strict level checks with ExplicitLevelImports]+             -> checkThLocalNameNoLift loc_gre_with_rdr++             | nameIsLocalOrFrom this_mod name+             -> checkThLocalTyName gre++             | otherwise -> pure ()        ; when (isDataConName name && not (isKindName name)) $            -- Any use of a promoted data constructor name (that is not            -- specifically exempted by isKindName) is illegal without the use@@ -556,7 +566,7 @@        ; when (isDataConName name && not (isPromoted ip)) $          -- NB: a prefix symbolic operator such as (:) is represented as HsTyVar.             addDiagnostic (TcRnUntickedPromotedThing $ UntickedConstructor Prefix name)-       ; return (HsTyVar noAnn ip (L loc $ WithUserRdr rdr_name name), unitFV name) }+       ; return (HsTyVar noAnn ip $ fmap greName <$> loc_gre_with_rdr, unitFV name) }  rnHsTyKi env ty@(HsOpTy _ prom ty1 l_op ty2)   = setSrcSpan (getLocA l_op) $@@ -702,7 +712,38 @@   pure (HsNumTy x i) rnHsTyLit (HsCharTy x c) = pure (HsCharTy x c) +{-+Note [Strict level checks with ExplicitLevelImports]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+Since the proposed change specification of `ExplicitLevelImports` [1] talks about+all identifiers as if they were created equally in the context of TemplateHaskell,+we want to adhere to that specification and at the same time use this unique+chance of being able to guard the "correct" behaviour behind an extension, without+breaking too many users. That is why, if ExplicitLevelImports is on, we+- do not allow non-well-levelled types to be imported+- do not allow locally defined type names to be used in an ill-levelled way, more+  most importantly, we do not allow locally defined names to be used in quotes. +When doing level checks, we historically have been glancing over some+not-well-levelled programs - e.g. the following program was historically+accepted from the perspective of the stage restriction:++type T = ExpQ+x = $(_ :: T)++However, when type-checking the splice `$(_ :: T)`, we found that `T`+had not yet been made part of the type-checking environment - we would+insert an ad-hoc check in `notFound` which would report the staging error.++See Note [Out of scope might be a staging error]++This is obviously not very rigorous - our "specification" of a program+being well-staged becomes "if the type checker needs the thing to be in scope+and it is not, the program is not well-staged, otherwise it is".++[1]: https://github.com/ghc-proposals/ghc-proposals/blob/8e4d0e9340c04b904373f9dfe5cbcebc354cd01f/proposals/0682-explicit-level-imports.rst+-}+ rnHsMultAnnWith :: (LocatedA (mult GhcPs) -> RnM (LocatedA (mult GhcRn), FreeVars))                   -> HsMultAnnOf (LocatedA (mult GhcPs)) GhcPs                   -> RnM (HsMultAnnOf (LocatedA (mult GhcRn)) GhcRn, FreeVars)@@ -745,13 +786,13 @@ -}  ---------------rnTyVar :: RnTyKiEnv -> RdrName -> RnM Name+rnTyVar :: RnTyKiEnv -> RdrName -> RnM GlobalRdrElt rnTyVar env rdr_name-  = do { name <- lookupTypeOccRn rdr_name-       ; checkNamedWildCard env name-       ; return name }+  = do { gre <- lookupTypeOccRn rdr_name+       ; checkNamedWildCard env $ greName gre+       ; return gre } -rnLTyVar :: LocatedN RdrName -> RnM (LocatedN Name)+rnLTyVar :: LocatedN RdrName -> RnM (LocatedN GlobalRdrElt) -- Called externally; does not deal with wildcards rnLTyVar (L loc rdr_name)   = do { tyvar <- lookupTypeOccRn rdr_name@@ -761,12 +802,13 @@ rnHsTyOp :: RnTyKiEnv -> SDoc -> LocatedN RdrName          -> RnM (LocatedN Name, FreeVars) rnHsTyOp env overall_ty (L loc op)-  = do { op' <- rnTyVar env op+  = do { opgre <- rnTyVar env op+       ; let opName = greName opgre        ; unlessXOptM LangExt.TypeOperators $-           if (op' `hasKey` eqTyConKey) -- See [eqTyCon (~) compatibility fallback] in GHC.Rename.Env+           if opName `hasKey` eqTyConKey -- See [eqTyCon (~) compatibility fallback] in GHC.Rename.Env            then addDiagnostic TcRnTypeEqualityRequiresOperators            else addErr $ TcRnIllegalTypeOperator overall_ty op-       ; return (L loc op', unitFV op') }+       ; return (L loc opName, unitFV opName) }  -------------- checkWildCard :: RnTyKiEnv
GHC/Rename/Module.hs view
@@ -2453,8 +2453,8 @@              bindLocalNames (maybeToList (hsLTyVarName resTv)) $              -- The return type variable scopes over the injectivity annotation              -- e.g.   type family F a = (r::*) | r -> a-             do { injFrom' <- rnLTyVar injFrom-                ; injTo'   <- mapM rnLTyVar injTo+             do { injFrom' <- fmap greName <$> rnLTyVar injFrom+                ; injTo'   <- mapM (fmap (fmap greName) . rnLTyVar) injTo                 -- Note: srcSpan is unchanged, but typechecker gets                 -- confused, l2l call makes it happy                 ; return $ L (l2l srcSpan) (InjectivityAnn x injFrom' injTo') }@@ -2495,7 +2495,7 @@    (injDecl', _) <- askNoErrs $ do      injFrom' <- rnLTyVar injFrom      injTo'   <- mapM rnLTyVar injTo-     return $ L srcSpan (InjectivityAnn x injFrom' injTo')+     return $ L srcSpan (InjectivityAnn x (fmap greName injFrom') (fmap (fmap greName) injTo'))    return $ injDecl'  {-
GHC/Rename/Names.hs view
@@ -471,11 +471,14 @@        -- not really correct as pkg_fs is unlikely to be a valid unit-id but        -- we will report the failure later...   where-    home_names  = map (\uid -> (uid, mkFastString <$> thisPackageName (homeUnitEnv_dflags (ue_findHomeUnitEnv uid unit_env)))) hpt_deps+    home_names =+      [ (uid, mkFastString <$> thisPackageName (homeUnitEnv_dflags (ue_findHomeUnitEnv uid unit_env)))+      | uid <- S.toList hpt_deps+      ]      unit_state = ue_homeUnitState unit_env -    hpt_deps :: [UnitId]+    hpt_deps :: S.Set UnitId     hpt_deps  = homeUnitDepends unit_state  
GHC/Rename/Pat.hs view
@@ -1285,7 +1285,8 @@  lookupTypeOccTPRnM :: RdrName -> TPRnM Name lookupTypeOccTPRnM rdr_name = liftRnFV $ do-  name <- lookupTypeOccRn rdr_name+  gre <- lookupTypeOccRn rdr_name+  let name = greName gre   pure (name, unitFV name)  rn_lty_pat :: LHsType GhcPs -> TPRnM (LHsType GhcRn)
GHC/Rename/Splice.hs view
@@ -1,6 +1,5 @@ {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeFamilies #-}-{-# LANGUAGE MultiWayIf #-}  module GHC.Rename.Splice (         rnTopSpliceDecls,@@ -35,12 +34,13 @@ import GHC.Types.Error import GHC.Types.Basic    ( TopLevelFlag, isTopLevel, maxPrec ) import GHC.Types.SourceText ( SourceText(..) )+import GHC.Types.ThLevelIndex import GHC.Utils.Outputable import GHC.Unit.Module import GHC.Types.SrcLoc import GHC.Rename.HsType ( rnLHsType ) -import Control.Monad    ( unless, when )+import Control.Monad    ( unless, when, void )  import {-# SOURCE #-} GHC.Rename.Expr ( rnLExpr ) @@ -181,12 +181,13 @@        }  rn_utbracket :: HsQuote GhcPs -> RnM (HsQuote GhcRn, FreeVars)-rn_utbracket (VarBr _ flg rdr_name)-  = do { name <- lookupOccRn (if flg then WL_Term else WL_Type) (unLoc rdr_name)-       ; let res_name = L (l2l (locA rdr_name)) (WithUserRdr (unLoc rdr_name) name)-       ; if flg then checkThLocalNameNoLift res_name else checkThLocalTyName name-       ; check_namespace flg name-       ; return (VarBr noExtField flg (noLocA name), unitFV name) }+rn_utbracket (VarBr _ is_value_name rdr_name)+  = do { gre <- lookupOccRnGRE (if is_value_name then WL_Term else WL_Type) (unLoc rdr_name)+       ; let loc_name = L (l2l (locA rdr_name)) (WithUserRdr (unLoc rdr_name) gre)+       ; let name = greName gre+       ; if is_value_name then checkThLocalNameNoLift loc_name else checkThLocalTyName gre+       ; check_namespace is_value_name $ greName gre+       ; return (VarBr noExtField is_value_name (fmap (greName . unwrapUserRdr) loc_name), unitFV name) }  rn_utbracket (ExpBr _ e) = do { (e', fvs) <- rnLExpr e                                 ; return (ExpBr noExtField e', fvs) }@@ -431,10 +432,11 @@  rnUntypedSplice (HsQuasiQuote _ quoter quote) flavour   = do  { -- Rename the quoter; akin to the HsVar case of rnExpr-        ; quoter' <- lookupLocatedOccRn WL_TermVariable quoter+        ; quoter' <- lookupLocatedOccRnGRE WL_TermVariable quoter         ; let res_name = WithUserRdr (unLoc quoter) <$> quoter'         ; checkThLocalNameNoLift res_name-        ; return (HsQuasiQuote (HsQuasiQuoteExt flavour) quoter' quote, unitFV (unLoc quoter')) }+        ; let loc_name = fmap greName quoter'+        ; return (HsQuasiQuote (HsQuasiQuoteExt flavour) loc_name quote, unitFV (unLoc loc_name)) }  --------------------- rnTypedSplice :: HsTypedSplice GhcPs -- Typed splice expression@@ -907,14 +909,14 @@       = vcat [ text "--" <+> ppr loc <> colon <+> text "Splicing" <+> text sd              , gen ] -checkThLocalTyName :: Name -> RnM ()-checkThLocalTyName name+checkThLocalTyName :: GlobalRdrElt -> RnM ()+checkThLocalTyName gre   | isUnboundName name   -- Do not report two errors for   = return ()            --   $(not_in_scope args)    | otherwise   = do  { traceRn "checkThLocalTyName" (ppr name)-        ; mb_local_use <- getCurrentAndBindLevel name+        ; mb_local_use <- getCurrentAndBindLevel gre         ; case mb_local_use of {              Nothing -> return () ;  -- Not a locally-bound thing              Just (top_lvl, bind_lvl, use_lvl) ->@@ -933,25 +935,29 @@                                                  <+> ppr use_lvl)         ; dflags <- getDynFlags         ; checkCrossLevelLiftingTy dflags top_lvl bind_lvl use_lvl use_lvl_idx name } } }+  where name = greName gre  -- | Check whether we are allowed to use a Name in this context (for TH purposes) -- In the case of a level incorrect program, attempt to fix it by using -- a Lift constraint.-checkThLocalNameWithLift :: LIdOccP GhcRn -> RnM (HsExpr GhcRn)+checkThLocalNameWithLift :: LocatedN (WithUserRdr GlobalRdrElt) -> RnM (HsExpr GhcRn) checkThLocalNameWithLift = checkThLocalName True  -- | Check whether we are allowed to use a Name in this context (for TH purposes) -- In the case of a level incorrect program, do not attempt to fix it by using -- a Lift constraint.-checkThLocalNameNoLift :: LIdOccP GhcRn -> RnM ()-checkThLocalNameNoLift name = checkThLocalName False name >> return ()+checkThLocalNameNoLift :: LocatedN (WithUserRdr GlobalRdrElt) -> RnM ()+checkThLocalNameNoLift = void . checkThLocalName False  -- | Implemenation of the level checks -- See Note [Template Haskell levels]-checkThLocalName :: Bool -> LIdOccP GhcRn -> RnM (HsExpr GhcRn)-checkThLocalName allow_lifting name_var+checkThLocalName :: Bool -> LocatedN (WithUserRdr GlobalRdrElt) -> RnM (HsExpr GhcRn)+checkThLocalName allow_lifting loc_gre   -- Exact and Orig names are not imported, so presumed available at all levels.-  | isExact (userRdrName (unLoc name_var)) || isOrig (userRdrName (unLoc name_var))+  -- whenever the user uses exact names, e.g. say @'mkNameG_v' "" "Foo" "bar"@,+  -- even though the 'mkNameG_v' here is essentially a quotation, we do not do+  -- level checks as we assume that the user was trying to bypass the level checks+  | isExact rdr || isOrig rdr   = return (HsVar noExtField name_var)   | isUnboundName name   -- Do not report two errors for   = return (HsVar noExtField name_var)            --   $(not_in_scope args)@@ -959,7 +965,7 @@   = return (HsVar noExtField name_var)   | otherwise   = do  {-          mb_local_use <- getCurrentAndBindLevel name+          mb_local_use <- getCurrentAndBindLevel $ unwrap loc_gre         ; case mb_local_use of {              Nothing -> return (HsVar noExtField name_var) ;  -- Not a locally-bound thing              Just (top_lvl, bind_lvl, use_lvl) ->@@ -968,13 +974,12 @@         ; let is_local                   | Just mod <- nameModule_maybe name = mod == cur_mod                   | otherwise = True-        ; traceRn "checkThLocalName" (ppr name <+> ppr bind_lvl <+> ppr use_lvl <+> ppr use_lvl)         ; dflags <- getDynFlags-        ; env <- getGlobalRdrEnv-        ; let mgre = lookupGRE_Name env name-        ; checkCrossLevelLifting dflags (LevelCheckSplice name mgre) top_lvl is_local allow_lifting bind_lvl use_lvl use_lvl_idx name_var } } }-  where-    name = getName name_var+        ; checkCrossLevelLifting dflags (LevelCheckSplice $ unLoc loc_gre) top_lvl is_local allow_lifting bind_lvl use_lvl use_lvl_idx name_var } } }+  where rdr = userRdrName $ unLoc name_var+        name_var = fmap greName <$> loc_gre+        name = unwrap name_var+        unwrap = unwrapUserRdr . unLoc  -------------------------------------- checkCrossLevelLifting :: DynFlags@@ -1001,15 +1006,17 @@   , xopt LangExt.ImplicitStagePersistence dflags = when (isExternalName name) (keepAlive name) >> return (HsVar noExtField name_var)   -- 4. Name is in a bracket, and lifting is allowed   | Brack _ pending <- use_lvl-  , any (use_lvl_idx >=) (Set.toList bind_lvl)+  , any (\bind_idx -> use_lvl_idx == incThLevelIndex bind_idx) (Set.toList bind_lvl)   , allow_lifting   = do-       let mgre = case reason of-                   LevelCheckSplice _ gre -> gre-                   _ -> Nothing+       let gre+             | LevelCheckSplice rdr <- reason+             = Just $! unwrapUserRdr rdr+             | otherwise+             = Nothing        (splice_name :: Name) <- newLocalBndrRn (noLocA unqualSplice)        let  pend_splice :: HsImplicitLiftSplice-            pend_splice = HsImplicitLiftSplice bind_lvl use_lvl_idx mgre name_var+            pend_splice = HsImplicitLiftSplice bind_lvl use_lvl_idx gre name_var        -- Warning for implicit lift (#17804)        addDetailedDiagnostic (TcRnImplicitLift name) 
GHC/Rename/Splice.hs-boot view
@@ -2,7 +2,7 @@  import GHC.Hs import GHC.Tc.Utils.Monad-import GHC.Types.Name (Name)+import GHC.Types.Name.Reader (WithUserRdr, GlobalRdrElt) import GHC.Types.Name.Set  @@ -15,4 +15,6 @@  rnTopSpliceDecls :: HsUntypedSplice GhcPs -> RnM ([LHsDecl GhcPs], FreeVars) -checkThLocalTyName :: Name -> RnM ()+checkThLocalTyName :: GlobalRdrElt -> RnM ()++checkThLocalNameNoLift :: LocatedN (WithUserRdr GlobalRdrElt) -> RnM ()
GHC/Rename/Unbound.hs view
@@ -12,6 +12,7 @@    , mkUnboundNameRdr    , mkUnboundGRE    , mkUnboundGRERdr+   , mkUnboundGREName    , isUnboundName    , reportUnboundName    , unknownNameSuggestions@@ -23,6 +24,8 @@    , LookingFor(..)    , unboundName    , unboundNameX+   , unboundGRE+   , unboundGREX    , unboundTermNameInTypes    , IsTermInTypes(..)    , notInScopeErr@@ -101,13 +104,22 @@ mkUnboundNameRdr rdr = mkUnboundName (rdrNameOcc rdr)  mkUnboundGRE :: OccName -> GlobalRdrElt-mkUnboundGRE occ = mkLocalGRE UnboundGRE NoParent $ mkUnboundName occ+mkUnboundGRE occ = mkUnboundGREName $ mkUnboundName occ  mkUnboundGRERdr :: RdrName -> GlobalRdrElt-mkUnboundGRERdr rdr = mkLocalGRE UnboundGRE NoParent $ mkUnboundNameRdr rdr+mkUnboundGRERdr rdr = mkUnboundGREName $ mkUnboundNameRdr rdr +mkUnboundGREName :: Name -> GlobalRdrElt+mkUnboundGREName = mkLocalGRE UnboundGRE NoParent+ reportUnboundName :: WhatLooking -> RdrName -> RnM Name reportUnboundName what_look rdr = unboundName (LF what_look WL_Anywhere) rdr++unboundGRE :: LookingFor -> RdrName -> RnM GlobalRdrElt+unboundGRE lf rdr = mkUnboundGREName <$> unboundName lf rdr++unboundGREX :: LookingFor -> RdrName -> [GhcHint] -> RnM GlobalRdrElt+unboundGREX lf rdr hints = mkUnboundGREName <$> unboundNameX lf rdr hints  unboundName :: LookingFor -> RdrName -> RnM Name unboundName lf rdr = unboundNameX lf rdr []
GHC/Runtime/Interpreter.hs view
@@ -737,7 +737,7 @@ getModBreaks hmi   | Just linkable <- homeModInfoByteCode hmi,     -- The linkable may have 'DotO's as well; only consider BCOs. See #20570.-    [cbc] <- linkableBCOs linkable+    [cbc] <- linkableAllBCOs linkable   = bc_breaks cbc   | otherwise   = Nothing -- probably object code
GHC/Runtime/Interpreter/Types.hs view
@@ -48,6 +48,7 @@ import GHCi.RemoteTypes import GHCi.Message         ( Pipe ) +import GHC.Data.FastString.Env import GHC.Platform #if defined(HAVE_INTERNAL_INTERPRETER) import GHC.Platform.Ways@@ -76,6 +77,9 @@    , interpSymbolCache :: !InterpSymbolCache       -- ^ LookupSymbol cache++  , interpStringCache :: !(MVar (FastStringEnv (RemotePtr ())))+      -- ^ MallocStrings cache   }  data InterpInstance
GHC/Stg/EnforceEpt.hs view
@@ -42,9 +42,6 @@  A binder is EPT when all the runtime pointers it binds are EPT. -Note that a lifted EPT pointer will never point to a thunk, nor will it be-tagged `000` (meaning "might be a thunk").- See https://gitlab.haskell.org/ghc/ghc/-/wikis/commentary/rts/haskell-execution/pointer-tagging for more information on pointer tagging. @@ -59,12 +56,16 @@ * In practice, GHC also guarantees that strict fields (and others) are EPT;   see Note [EPT enforcement]. -Caveat:-Currently, the proper tag for builtin *unlifted* data types such as `Array#` is-not `001` but `000`, which is not a proper tag for lifted data.-This means that UnliftedRep is not a proper sub-rep of LiftedRep.-SG thinks it would be good to fix this; see #21792.+Wrinkles: +EPT1:  The proper tag for builtin *unlifted* data types such as `Array#` is+       not `001` but `000`, which is not a proper tag for lifted data.+       This means that UnliftedRep is not a proper sub-rep of LiftedRep.+       SG thinks it would be good to fix this; see #21792.+EPT2:  The proper tag for PAPs is `000`, so there are values from lifted data types+       that are EPT with a zero tag.+EPT3:  Non-pointer values don't have a tag at all, but we still treat them as EPT.+ Note [EPT enforcement] ~~~~~~~~~~~~~~~~~~~~~~ The goal of EnforceEPT pass is to mark as many binders as possible as EPT@@ -251,19 +252,40 @@  {- Note [TagInfo of functions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-The purpose of tag inference is really to figure out when we don't have to enter-value closures. There the meaning of the tag is fairly obvious.-For functions we never make use of the tag info so we have two choices:-* Treat them as TagDunno-* Treat them as TagProper (as they *are* tagged with their arity) and be really-  careful to make sure we still enter them when needed.-As it makes little difference for runtime performance I've treated functions as TagDunno in a few places where-it made the code simpler. But besides implementation complexity there isn't any reason-why we couldn't be more rigorous in dealing with functions.+'TagFun' represents an evaluated function and carries the return-value TagInfo+for saturated calls. See Note [TagSig and TagInfo] in GHC.Stg.EnforceEpt.TagSig. -NB: It turned in #21193 that PAPs get tag zero, so the tag check can't be omitted for functions.-So option two isn't really an option without reworking this anyway.+Join points (StgLetNoEscape) are treated like functions: they are jumped to,+never entered via a closure pointer. Even nullary join points get TagFun+rather than TagVal TagDunno, so their return-value info flows through. +Additionally we also special case bottoming functions.+See Note [Bottom functions are TagBottoming].++Function values when properly tagged have either their arity, 1 for very large+arities, or zero for PAPs (#21193) as tag. However the runtime currently doesn't+maintain the EPT status of function pointers. So while we keep track of+evaluated function binders using 'TagFun' this has a weaker guarantee than for+values. For functions it only represents a pointer to an evaluated function, but+doesn't give any guarantee about the function's pointer tag.++Sadly because PAPs get tag zero (#21193), other issues in the RTS (#21193) and+the potential of over/underapplication of arguments, even evaluated function+binders still require inspection of their closure before they can be applied.+That is, even if we have++    case f of f' -> ... f' x ...++the code for `f' x` can't be made meaningfully more efficient by knowing `f'` is+already evaluated.++However tracking evaluation status for functions is still worthwhile, as we rely+on the EPT pass to force strict constructor fields. For an application+`StrictJust f` we would usually insert an eval of `f` around the constructor+application. However if we infer `f` to be already evaluated we can avoid this,+which was a significant performance benefit in #27005. Similarly we can still+turn redundant eval-cases on functions into a no-op.+ Note [EPT enforcement debugging] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ There is a flag -dtag-inference-checks which inserts various@@ -299,14 +321,21 @@   We make this differentiation in `mkLetSig` where we simply never assume   lets are tagged when targeting bytecode. -b) When referencing ids from other modules the Cmm backend will try to put a-   proper tag on these references through various means. When doing analysis we-   usually predict these cases to improve precision of the analysis.-   But to my knowledge the bytecode generator makes no such attempts so we must-   not infer imported bindings as tagged.-   This is handled in GHC.Stg.EnforceEpt.Types.lookupInfo+b) When referencing ids from other modules the Cmm based backends ensure top+   level binders are properly tagged if they are constructors. +   This is not true for the bytecode generator, which gives fewer guarantees about+   what it tags. So we assume the safe, but slightly less efficient default of+   no imported binding being tagged when generating bytecode. +   This is handled in GHC.Stg.EnforceEpt.Types.argTagInfo++ Eventually we will want to update the Analysis and bco code gen to uphold and+ take advantage of tag inference at least to some degree. But for now it's+ not a perf benefit for interpreted code, and essentially only run to uphold+ the "strict field invariant"/EPT Invariant described in EPT enforcement.++ -}  {- *********************************************************************@@ -327,7 +356,7 @@      -- Rewrite STG to uphold the strict field invariant     us_t <- mkSplitUniqSupply 't'-    let rewritten_binds = {-# SCC "StgEptRewrite" #-} rewriteTopBinds this_mod us_t stg_binds_w_tags :: [TgStgTopBinding]+    let rewritten_binds = {-# SCC "StgEptRewrite" #-} rewriteTopBinds for_bytecode this_mod us_t stg_binds_w_tags :: [TgStgTopBinding]      return (rewritten_binds,export_tag_info) @@ -351,7 +380,6 @@  inferTags :: Bool -> [GenStgTopBinding 'CodeGen] -> [GenStgTopBinding 'InferTaggedBinders] inferTags for_bytecode binds =-  -- pprTrace "Binds" (pprGenStgTopBindings shortStgPprOpts $ binds) $   snd (mapAccumL inferTagTopBind (initEnv for_bytecode) binds)  -----------------------@@ -379,18 +407,22 @@     !fun_arity = idArity fun     info          -- It's important that we check for bottoms before all else.-         -- See Note [Bottom functions are TagTagged] and #24806 for why.+         -- See Note [Bottom functions are TagBottoming] and #24806 for why.          | isDeadEndAppSig (idDmdSig fun) (length args)-         = TagTagged+         = TagBottoming -         | fun_arity == 0 -- Unknown arity => Thunk or unknown call+         | not (isJoinId fun) -- zero arity join ids behave like functions NOT thunks.+         , fun_arity == 0 -- Unknown arity => Thunk or unknown call          = TagDunno -         | Just (TagSig res_info) <- tagSigInfo (idInfo fun)+         -- Imported function with known return tag+         | Just (TagFun res_info) <- tagSigInfo (idInfo fun)          , fun_arity == length args  -- Saturated+         , not (te_bytecode env) -- #27842          = res_info -         | Just (TagSig res_info) <- lookupSig env fun+         -- Local function with known return tag+         | Just res_info <- lookupReturnInfo env fun          , fun_arity == length args  -- Saturated          = res_info @@ -402,7 +434,7 @@   = (inferConTag env con args, StgConApp con cn args tys)  inferTagExpr _ (StgLit l)-  = (TagTagged, StgLit l)+  = (TagEPT, StgLit l)  inferTagExpr env (StgTick tick body)   = (info, StgTick tick body')@@ -436,7 +468,7 @@         mk_bndr :: BinderP p -> TagInfo -> (Id, TagSig)         mk_bndr tup_bndr tup_info =             --  pprTrace "mk_ubx_bndr_info" ( ppr bndr <+> ppr info ) $-            (getBinderId in_env tup_bndr, TagSig tup_info)+            (getBinderId in_env tup_bndr, TagVal tup_info)         -- no case binder in alt_env here, unboxed tuple binders are dead after unarise         alt_env = extendSigEnv in_env bndrs'         (info, rhs') = inferTagExpr alt_env rhs@@ -468,16 +500,16 @@                   , let (alt_env,bndrs') = addAltBndrInfo case_env con bndrs                         (info, rhs') = inferTagExpr alt_env rhs                   ]-        alt_info = foldr combineAltInfo TagTagged infos+        alt_info = foldr combineAltInfo TagBottoming infos     in ( alt_info, StgCase scrut' bndr' ty alts')   where     -- Single unboxed tuple alternative     scrut_infos bndrs = case scrut_info of-      TagTagged -> Just $ replicate (length bndrs) TagProper+      TagBottoming -> Just $ replicate (length bndrs) TagBottoming       TagTuple infos -> Just infos       _ -> Nothing     (scrut_info, scrut') = inferTagExpr in_env scrut-    bndr' = (getBinderId in_env bndr, TagSig TagProper)+    bndr' = (getBinderId in_env bndr, TagVal TagEPT)  -- Compute binder sigs based on the constructors strict fields. -- NB: Not used if we have tuple info from the scrutinee.@@ -493,7 +525,7 @@     mk_bndr :: (BinderP p -> StrictnessMark -> (Id, TagSig))     mk_bndr bndr mark       | isUnliftedType (idType id) || isMarkedStrict mark-      = (id, TagSig TagProper)+      = (id, TagVal TagEPT)       | otherwise       = noSig env bndr         where@@ -513,7 +545,7 @@     (env', StgNonRec (id, out_sig) rhs')   where     id   = getBinderId in_env bndr-    (in_sig,rhs') = inferTagRhs id in_env rhs+    (in_sig, rhs') = inferTagRhs id in_env rhs     out_sig = mkLetSig in_env in_sig     env' = extendSigEnv in_env [(id, out_sig)] @@ -526,13 +558,12 @@     init_sigs         = map (initSig) $ zip in_ids rhss     (out_env, pairs') = go in_env init_sigs rhss -    go :: forall q. (OutputableInferPass q , InferExtEq q) => TagEnv q -> [TagSig] -> [GenStgRhs q]-                 -> (TagSigEnv, [((Id,TagSig), GenStgRhs 'InferTaggedBinders)])+    go :: forall q. (OutputableInferPass q , InferExtEq q)+       => TagEnv q -> [TagSig] -> [GenStgRhs q]+       -> (TagSigEnv, [((Id,TagSig), GenStgRhs 'InferTaggedBinders)])     go go_env in_sigs go_rhss-      --   | pprTrace "go" (ppr in_ids $$ ppr in_sigs $$ ppr out_sigs $$ ppr rhss') False-      --  = undefined        | in_sigs == out_sigs = (te_env rhs_env, out_bndrs `zip` rhss')-       | otherwise     = go env' out_sigs rhss'+       | otherwise           = go env' out_sigs rhss'        where          in_bndrs = in_ids `zip` in_sigs          out_bndrs = map updateBndr in_bndrs -- TODO: Keeps in_ids alive@@ -542,25 +573,28 @@           anaRhs :: Id -> GenStgRhs q -> (TagSig, GenStgRhs 'InferTaggedBinders)          anaRhs bnd rhs =-            let (sig_rhs,rhs') = inferTagRhs bnd rhs_env rhs+            let (sig_rhs, rhs') = inferTagRhs bnd rhs_env rhs             in (mkLetSig go_env sig_rhs, rhs')            updateBndr :: (Id,TagSig) -> (Id,TagSig)          updateBndr (v,sig) = (setIdTagSig v sig, sig) +-- Initial signature for the fixpoint loop. initSig :: forall p. (Id, GenStgRhs p) -> TagSig--- Initial signature for the fixpoint loop-initSig (_bndr, StgRhsCon {})               = TagSig TagTagged-initSig (bndr, StgRhsClosure _ _ _ _ _ _) =-  fromMaybe defaultSig (idTagSig_maybe bndr)-  where defaultSig = (TagSig TagTagged)+initSig (_bndr, StgRhsCon {})+  = TagVal TagBottoming+initSig (bndr, StgRhsClosure _ _ _ bndrs _ _)+  | notNull bndrs || isJoinId bndr+  = fromMaybe (TagFun TagBottoming) (idTagSig_maybe bndr)+  | otherwise  -- thunk+  = fromMaybe (TagVal TagBottoming) (idTagSig_maybe bndr) -{- Note [Bottom functions are TagTagged]+{- Note [Bottom functions are TagBottoming] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-If we have a function with two branches with one+If we have a function with two branches with one branch being bottom, and the other returning a tagged-unboxed tuple what is the result? We give it TagTagged!+unboxed tuple what is the result? We give it TagBottoming! To answer why consider this function:  foo :: Bool -> (# Bool, Bool #)@@ -568,21 +602,43 @@     True -> (# True,True #)     False -> undefined -The true branch is obviously tagged. The other branch isn't.-We want to treat the *result* of foo as tagged as well so that-the combination of the branches also is tagged if all non-bottom-branches are tagged.-This is safe because the function is still always called/entered as long-as it's applied to arguments. Since the function will never return we can give-it safely any tag sig we like.-So we give it TagTagged, as it allows the combined tag sig of the case expression-to be the combination of all non-bottoming branches.+The true branch obviously returns tagged components. The other branch is bottom.+We want to treat the components in the *result* returned by foo as tagged.+Because at a call site like: -NB: After the analysis is done we go back to treating bottoming functions as-untagged to ensure they are evaluated as expected in code like:+    case foo e of+        (# x, y #) ->+            case x of+                ... -  case bottom_id of { ...}+Either `foo` will have evaluated undefined or blown up. Or we will bind x and y+to tagged pointers. A fact we take advantage of to optimize `case x of`. +The rule is then simple. A combination of the alternatives of the same case has+tagged components if all non-bottom branches have tagged components.++To represent the bottoming alternatives we use TagBottoming. Which says all its+components are tagged. Now the same is true if we have:++foo :: Bool -> (# Bool, Bool #)+foo x = case x of+    True -> (# True,True #)+    False -> willCrash x++We want to check:++* Is `willCrash x` bottom?+* If the whole case expression *does* return are the tuple components tagged?++The first check is done by inferTagExpr, which needs to check if willCrash is+applied to enough arguments to crash. If so we get TagBottoming for the case+alternative. Which when combined with TagTuple [TagEPT, TagEPT] gives the+desired TagTuple [TagEPT, TagEPT] for the overall case expression.++NB: If there is just one rhs it's handled by inferTagRhs which will give+SigFun TagBottoming for `foo x= willCrash x` in the same fashion as inferTagExpr does.++ -}  -----------------------------@@ -593,13 +649,20 @@   -> GenStgRhs p -- ^   -> (TagSig, GenStgRhs 'InferTaggedBinders) inferTagRhs bnd_id in_env (StgRhsClosure ext cc upd bndrs body typ)-  | isDeadEndId bnd_id && (notNull) bndrs-  -- See Note [Bottom functions are TagTagged]-  = (TagSig TagTagged, StgRhsClosure ext cc upd out_bndrs body' typ)-  | otherwise-  = --pprTrace "inferTagRhsClosure" (ppr (_top, _grp_ids, env,info')) $-    (TagSig info', StgRhsClosure ext cc upd out_bndrs body' typ)+  | isDeadEndId bnd_id && is_fun_or_join+  -- See Note [Bottom functions are TagBottoming]+  = ( TagFun TagBottoming+    , StgRhsClosure ext cc upd out_bndrs body' typ)+  | is_fun_or_join+  = ( TagFun info+    , StgRhsClosure ext cc upd out_bndrs body' typ)+  | otherwise  -- thunk (never a join point)+  = ( TagVal TagDunno+    , StgRhsClosure ext cc upd out_bndrs body' typ)   where+    -- Join points are treated like functions. See Note [TagInfo of functions]+    is_fun_or_join = notNull bndrs || isJoinId bnd_id+     out_bndrs       | Just marks <- idCbvMarks_maybe bnd_id       -- Sometimes an we eta-expand foo with additional arguments after ww, and we also trim@@ -610,37 +673,29 @@      env' = extendSigEnv in_env out_bndrs     (info, body') = inferTagExpr env' body-    info'-      -- It's a thunk-      | null bndrs-      = TagDunno-      -- TODO: We could preserve tuple fields for thunks-      -- as well. But likely not worth the complexity. -      | otherwise  = info-     mkArgSig :: BinderP p -> CbvMark -> (Id,TagSig)     mkArgSig bndp mark =       let id = getBinderId in_env bndp           tag = case mark of-            MarkedCbv -> TagProper+            MarkedCbv -> TagEPT             _-              | isUnliftedType (idType id) -> TagProper+              | isUnliftedType (idType id) -> TagEPT               | otherwise -> TagDunno-      in (id, TagSig tag)+      in (id, TagVal tag)  inferTagRhs _ env _rhs@(StgRhsCon cc con cn ticks args typ) -- Constructors, which have untagged arguments to strict fields -- become thunks. We encode this by giving changing RhsCon nodes the info TagDunno   = --pprTrace "inferTagRhsCon" (ppr grp_ids) $-    (TagSig (inferConTag env con args), StgRhsCon cc con cn ticks args typ)+    (TagVal (inferConTag env con args), StgRhsCon cc con cn ticks args typ)  -- Adjust let semantics to the targeted backend. -- See Note [EPT enforcement for interpreted code] mkLetSig :: TagEnv p -> TagSig -> TagSig mkLetSig env in_sig-  | for_bytecode = TagSig TagDunno-  | otherwise = in_sig+  | for_bytecode = TagVal TagDunno+  | otherwise    = in_sig   where     for_bytecode = te_bytecode env @@ -648,52 +703,53 @@ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @inferConTag@ will infer the proper tag signature for a binding who's RHS is a constructor or a StgConApp expression.-Usually these will simply be TagProper. But there are exceptions.+Usually these will simply be TagEPT. But there are exceptions. If any of the fields in the constructor are strict, but any argument to these fields is not tagged then we will have to case on the argument before storing in the constructor. Which means for let bindings the RHS turns into a thunk which obviously is no longer properly tagged. For example we might start with: -    let x<TagDunno> = f ...-    let c<TagProper> = StrictPair x True+    let x<TagVal[TagDunno]> = f ...+    let c<TagVal[TagEPT]> = StrictPair x True  But we know during the rewrite stage x will need to be evaluated in the RHS of `c` so we will infer: -    let x<TagDunno> = f ...-    let c<TagDunno> = StrictPair x True+    let x<TagVal[TagDunno]> = f ...+    let c<TagVal[TagDunno]> = StrictPair x True  Which in the rewrite stage will then be rewritten into: -    let x<TagDunno> = f ...-    let c<TagDunno> = case x of x' -> StrictPair x' True+    let x<TagVal[TagDunno]> = f ...+    let c<TagVal[TagDunno]> = case x of x' -> StrictPair x' True  The other exception is unboxed tuples. These will get a TagTuple signature with a list of TagInfo about their individual binders as argument. As example: -    let c<TagProper> = True-    let x<TagDunno> = ...-    let f<?> z = case z of z'<TagProper> -> (# c, x #)+    let c<TagVal[TagEPT]> = True+    let x<TagVal[TagDunno]> = ...+    let f<?> z = case z of z'<TagVal[TagEPT]> -> (# c, x #) -Here we will infer for f the Signature <TagTuple[TagProper,TagDunno]>.+Here we will infer for f the Signature <TagFun[TagTuple[TagEPT,TagDunno]]>. This information will be used if we scrutinize a saturated application of `f` in order to determine the taggedness of the result. That is for `case f x of (# r1,r2 #) -> rhs` we can infer-r1<TagProper> and r2<TagDunno> which allows us to skip all tag checks on `r1`+r1<TagVal[TagEPT]> and r2<TagVal[TagDunno]> which allows us to skip all tag checks on `r1` in `rhs`.  Things get a bit more complicated with nesting: -    let closeFd<TagTuple[...]> = ...+    let closeFd<TagFun[...]> = ...     let f x = ...         case x of           _ -> Solo# closeFd -The "natural" signature for the Solo# branch in `f` would be <TagTuple[TagTuple[...]]>.-But we flatten this out to <TagTuple[TagDunno]> for the time being as it improves compile-time and there doesn't seem to huge benefit to doing differently.+We only keep track of function return types for bindings, not values:+TagInfo has no constructor for "function with return info". Therefore the+signature of `f` becomes <TagFun[TagTuple[TagEPT]]>. We lose the information+about the return type of `closeFd`.    -} @@ -711,7 +767,7 @@     --     text "info:" <> ppr info) $     info   where-    info = if any arg_needs_eval strictArgs then TagDunno else TagProper+    info = if any arg_needs_eval strictArgs then TagDunno else TagEPT     strictArgs = zipEqual args (dataConRuntimeRepStrictness con) :: ([(StgArg, StrictnessMark)])     arg_needs_eval (arg,strict)       -- lazy args@@ -720,10 +776,10 @@       -- banged args need to be tagged, or require eval       = not (isTaggedInfo tag) -    flatten_arg_tag (TagTagged) = TagProper-    flatten_arg_tag (TagProper ) = TagProper-    flatten_arg_tag (TagTuple _) = TagDunno -- See Note [Constructor TagSigs]-    flatten_arg_tag (TagDunno) = TagDunno+    flatten_arg_tag TagBottoming    = TagEPT+    flatten_arg_tag TagEPT          = TagEPT+    flatten_arg_tag (TagTuple _)    = TagDunno -- See Note [Constructor TagSigs]+    flatten_arg_tag TagDunno        = TagDunno   collectExportInfo :: [GenStgTopBinding 'InferTaggedBinders] -> NameEnv TagSig@@ -736,15 +792,14 @@     collect (StgTopLifted bnd) =       case bnd of         StgNonRec (id,sig) _rhs-          | TagSig TagDunno <- sig -> []+          | TagVal TagDunno     <- sig -> []+          | TagVal TagBottoming <- sig -> []           | otherwise -> [(idName id,sig)]         StgRec bnds -> collectRec bnds      collectRec :: [(BinderP 'InferTaggedBinders, rhs)] -> [(Name,TagSig)]     collectRec [] = []-    collectRec (bnd:bnds)-      | (p,_rhs)  <- bnd-      , (id,sig) <- p-      , TagSig TagDunno <- sig-      = (idName id,sig) : collectRec bnds-      | otherwise = collectRec bnds+    collectRec (((id,sig), _rhs) : bnds)+      | TagVal TagDunno     <- sig = collectRec bnds+      | TagVal TagBottoming <- sig = collectRec bnds+      | otherwise                  = (idName id, sig) : collectRec bnds
GHC/Stg/EnforceEpt/Rewrite.hs view
@@ -6,6 +6,7 @@ {-# LANGUAGE DataKinds                  #-} {-# LANGUAGE GADTs                      #-} {-# LANGUAGE TypeFamilies               #-}+{-# LANGUAGE UnboxedTuples              #-}  module GHC.Stg.EnforceEpt.Rewrite (rewriteTopBinds, rewriteOpApp) where@@ -16,7 +17,7 @@ import GHC.Types.Basic     ( CbvMark (..), isMarkedCbv                            , TopLevelFlag(..), isTopLevel ) import GHC.Types.Id-import GHC.Types.Name+import GHC.Types.Name ( nameIsLocalOrFrom ) import GHC.Types.Unique.Supply import GHC.Types.Unique.FM import GHC.Types.RepType@@ -25,10 +26,7 @@  import GHC.Core.DataCon import GHC.Core            ( AltCon(..) )-import GHC.Core.Type--import GHC.StgToCmm.Types-import GHC.StgToCmm.Closure (importedIdLFInfo)+import GHC.Core.Type       ( definitelyLiftedType )  import GHC.Stg.Utils import GHC.Stg.Syntax as StgSyn@@ -37,16 +35,55 @@ import GHC.Utils.Panic  import GHC.Utils.Outputable-import GHC.Utils.Monad.State.Strict import GHC.Utils.Misc  import GHC.Stg.EnforceEpt.Types  import Control.Monad+import GHC.Exts (oneShot)+import Data.Traversable (mapAccumM) -newtype RM a = RM { unRM :: (State (UniqFM Id TagSig, UniqSupply, Module, IdSet) a) }-    deriving (Functor, Monad, Applicative)+-- | Constant for whole module+data RmModInfo = RmModInfo { rm_mod :: !Module, rm_for_interpreter :: !Bool } +type SigEnv = UniqFM Id TagSig+data RmEnv = RmEnv { rm_fvs :: IdSet, rm_sig_env :: !(SigEnv) }++newtype RM a = RM { unRM :: RmModInfo -> RmEnv -> UniqSupply -> (# UniqSupply, a #) }++instance Functor RM where+    fmap f (RM x) = RM $ oneShot $ \info -> oneShot $ \env -> oneShot $ \us ->+        case x info env us of+            (# !us1, !x' #) ->+                let !r = f x'+                in (# us1, r #)++instance Applicative RM where+    (RM f) <*> (RM x) = RM $ oneShot $ \info -> oneShot $ \env -> oneShot $ \us ->+        case f info env us of+            (# !us1, !f' #) ->+                case x info env us1 of+                    (# !us2, !x' #) ->+                        let !r = f' x'+                        in (# us2, r #)+    pure !x = RM $ \_ !_env !us -> (# us, x #)++-- See Note [The one-shot state monad trick] in GHC.Utils.Monad+instance Monad RM where+    RM x >>= f = RM $ oneShot $ \info -> oneShot $ \env -> oneShot $ \us ->+        case x info env us of+            (# !us1, !x' #) -> case (f x') of RM r -> r info env us1++-- | runRM this_mod for_bytecode us+runRM :: Module -> Bool -> UniqSupply -> RM a -> a+runRM mod for_bytecode us act  =+    case (unRM act)+            (RmModInfo { rm_mod = mod, rm_for_interpreter = for_bytecode })+            (RmEnv { rm_fvs = emptyVarSet, rm_sig_env = emptyUFM })+            us+        of+    (# _, r #) -> r+ ------------------------------------------------------------ -- Add cases around strict fields where required. ------------------------------------------------------------@@ -110,31 +147,32 @@ --------------------------------  instance MonadUnique RM where-    getUniqueSupplyM = RM $ do-        (m, us, mod,lcls) <- get-        let (us1, us2) = splitUniqSupply us-        (put) (m,us2,mod,lcls)-        return us1--getMap :: RM (UniqFM Id TagSig)-getMap = RM $ ((\(fst,_,_,_) -> fst) <$> get)+    getUniqueSupplyM = RM $ \_ _env us ->+        case splitUniqSupply us of+            (us1, us2) -> (# us2, us1 #) -setMap :: (UniqFM Id TagSig) -> RM ()-setMap !m = RM $ do-    (_,us,mod,lcls) <- get-    put (m, us,mod,lcls)+getSigEnv :: RM SigEnv+getSigEnv = RM $ \_ env us -> (# us, rm_sig_env env #) -getMod :: RM Module-getMod = RM $ ( (\(_,_,thrd,_) -> thrd) <$> get)+{-# INLINE withSigEnv #-}+withSigEnv :: SigEnv-> RM a -> RM a+withSigEnv !m (RM f)= RM $ \mi env us -> f mi env { rm_sig_env = m} us  getFVs :: RM IdSet-getFVs = RM $ ((\(_,_,_,lcls) -> lcls) <$> get)+getFVs = RM $ \_ env us -> (# us, rm_fvs env #) -setFVs :: IdSet -> RM ()-setFVs !fvs = RM $ do-    (tag_map,us,mod,_lcls) <- get-    put (tag_map, us,mod,fvs)+{-# INLINE withFVs #-}+withFVs :: IdSet -> RM a -> RM a+withFVs !fvs (RM f)= RM $ \mi env us -> f mi env { rm_fvs = fvs } us +getMod :: RM Module+getMod = RM $ \info _env us -> (# us, rm_mod info #)++-- | When generating bytecode certain bindings might be untagged. So we have to+-- have a way to check for that.+getForBytecode :: RM Bool+getForBytecode = RM $ \info _env us -> (# us, rm_for_interpreter info #)+ -- Rewrite the RHS(s) while making the id and it's sig available -- to determine if things are tagged/need to be captured as FV. withBind :: TopLevelFlag -> GenStgBinding 'InferTaggedBinders -> RM a -> RM a@@ -143,66 +181,50 @@     let (bnds,_rhss) = unzip binds :: ([(Id, TagSig)], [GenStgRhs 'InferTaggedBinders])     withBinders top_flag bnds cont -addTopBind :: GenStgBinding 'InferTaggedBinders -> RM ()+addTopBind :: GenStgBinding 'InferTaggedBinders -> RM SigEnv addTopBind (StgNonRec (id, tag) _) = do-    s <- getMap+    s <- getSigEnv     -- pprTraceM "AddBind" (ppr id)-    setMap $ addToUFM s id tag-    return ()+    pure $! addToUFM s id tag addTopBind (StgRec binds) = do     let (bnds,_rhss) = unzip binds-    !s <- getMap+    !s <- getSigEnv     -- pprTraceM "AddBinds" (ppr $ map fst bnds)-    setMap $! addListToUFM s bnds+    pure $! addListToUFM s bnds  withBinder :: TopLevelFlag ->  (Id, TagSig) -> RM a -> RM a withBinder top_flag (id,sig) cont = do-    oldMap <- getMap-    setMap $ addToUFM oldMap id sig-    a <- if isTopLevel top_flag+    sig_env <- getSigEnv+    withSigEnv (addToUFM sig_env id sig) $ do+        if isTopLevel top_flag             then cont             else withLcl id cont-    setMap oldMap-    return a  withBinders :: TopLevelFlag -> [(Id, TagSig)] -> RM a -> RM a withBinders TopLevel sigs cont = do-    oldMap <- getMap-    setMap $ addListToUFM oldMap sigs-    a <- cont-    setMap oldMap-    return a+    sig_env <- getSigEnv+    withSigEnv (addListToUFM sig_env sigs) cont withBinders NotTopLevel sigs cont = do-    oldMap <- getMap-    oldFvs <- getFVs-    setMap $ addListToUFM oldMap sigs-    setFVs $ extendVarSetList oldFvs (map fst sigs)-    a <- cont-    setMap oldMap-    setFVs oldFvs-    return a+    sig_env <- getSigEnv+    fvs <- getFVs+    withSigEnv (addListToUFM sig_env sigs) $+        withFVs (extendVarSetList fvs (map fst sigs)) cont  -- | Compute the argument with the given set of ids treated as requiring capture -- as free variables. withClosureLcls :: DIdSet -> RM a -> RM a withClosureLcls fvs act = do     old_fvs <- getFVs-    let !fvs' = nonDetStrictFoldDVarSet (flip extendVarSet) old_fvs fvs-    setFVs fvs'-    !r <- act-    setFVs old_fvs-    return r+    withFVs+        (nonDetStrictFoldDVarSet (flip extendVarSet) old_fvs fvs)+        act  -- | Compute the argument with the given id treated as requiring capture -- as free variables in closures. withLcl :: Id -> RM a -> RM a withLcl fv act = do     old_fvs <- getFVs-    let !fvs' = extendVarSet old_fvs fv-    setFVs fvs'-    !r <- act-    setFVs old_fvs-    return r+    withFVs (extendVarSet old_fvs fv) act  {- Note [Tag inference for interactive contexts] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~@@ -241,52 +263,26 @@ For this reason we assert that we are running in interactive mode if a lookup fails. -} isTagged :: Id -> RM Bool-isTagged v-    -- See Note [Bottom functions are TagTagged]-    | isDeadEndId v = pure False-    | otherwise = do+isTagged v = do+    for_bytecode <- getForBytecode     this_mod <- getMod-    -- See Note [Tag inference for interactive contexts]-    let lookupDefault v = assertPpr (isInteractiveModule this_mod)-                                    (text "unknown Id:" <> ppr this_mod <+> ppr v)-                                    (TagSig TagDunno)-    case nameIsLocalOrFrom this_mod (idName v) of-        True-            | definitelyUnliftedType (idType v)-              -- NB: v might be the Id of a representation-polymorphic join point,-              -- so we shouldn't use isUnliftedType here. See T22212.-            -> return True-            | otherwise -> do -- Local binding-                !s <- getMap-                let !sig = lookupWithDefaultUFM s (lookupDefault v) v-                return $ case sig of-                    TagSig info ->-                        case info of-                            TagDunno -> False-                            TagProper -> True-                            TagTagged -> True-                            TagTuple _ -> True -- Consider unboxed tuples tagged.-        -- Imported-        False -> return $!-                -- Determine whether it is tagged from the LFInfo of the imported id.-                -- See Note [The LFInfo of Imported Ids]-                case importedIdLFInfo v of-                    -- Function, applied not entered.-                    LFReEntrant {}-                        -> True-                    -- Thunks need to be entered.-                    LFThunk {}-                        -> False-                    -- LFCon means we already know the tag, and it's tagged.-                    LFCon {}-                        -> True-                    LFUnknown {}-                        -> False-                    LFUnlifted {}-                        -> True-                    LFLetNoEscape {}-                    -- Shouldn't be possible. I don't think we can export letNoEscapes-                        -> True+    s <- getSigEnv+    let get_env_sig = lookupUFM s+    massertPpr+        -- Assert the env is complete for local lifted binders, which means either+        -- - The binder is present in the env+        -- - The binder is not a local lifted binder *or* comes from a ghci context+        (isJust (get_env_sig v)+            -- See Note [Tag inference for interactive contexts]+            || isInteractiveModule this_mod+            || not (nameIsLocalOrFrom this_mod (idName v))+            || not (definitelyLiftedType (idType v)))+               (text "unknown Id:" <> ppr this_mod <+> ppr v)+    -- TODO: We could refactor the whole pass such that we also set id_tagSig+    -- for every imported id. But this likely comes with a heavy allocation+    -- overhead so for now we just ensure to use the same logic across analysis+    -- and rewriter.+    pure $! isTaggedInfo $ argTagInfo for_bytecode (get_env_sig v) (StgVarArg v)   isArgTagged :: StgArg -> RM Bool@@ -303,18 +299,22 @@ ---------------------------  -rewriteTopBinds :: Module -> UniqSupply -> [GenStgTopBinding 'InferTaggedBinders] -> [TgStgTopBinding]-rewriteTopBinds mod us binds =-    let doBinds = mapM rewriteTop binds--    in evalState (unRM doBinds) (mempty, us, mod, mempty)+rewriteTopBinds :: Bool -- ^ Generating bytecode?+                -> Module -> UniqSupply -> [GenStgTopBinding 'InferTaggedBinders] -> [TgStgTopBinding]+rewriteTopBinds for_bytecode mod us binds =+    runRM mod for_bytecode us $ do+        snd <$> (mapAccumM rewriteTop mempty binds) -rewriteTop :: InferStgTopBinding -> RM TgStgTopBinding-rewriteTop (StgTopStringLit v s) = return $! (StgTopStringLit v s)-rewriteTop (StgTopLifted bind)   = do+rewriteTop :: SigEnv -> InferStgTopBinding -> RM (SigEnv, TgStgTopBinding)+rewriteTop sig_env (StgTopStringLit v s) = return $! (sig_env, StgTopStringLit v s)+rewriteTop sig_env (StgTopLifted bind)   = do     -- Top level bindings can, and must remain in scope-    addTopBind bind-    (StgTopLifted) <$!> (rewriteBinds TopLevel bind)+    -- We use withSigEnv inside rewriteTop per binding to avoid+    -- allocating one withEnv continuation per top binder.+    withSigEnv sig_env $ do+        sig_env <- addTopBind bind+        !binds <- withSigEnv sig_env (rewriteBinds TopLevel bind)+        pure (sig_env, StgTopLifted binds)  -- For top level binds, the wrapper is guaranteed to be `id` rewriteBinds :: TopLevelFlag -> InferStgBinding -> RM (TgStgBinding)@@ -388,7 +388,7 @@ rewriteId :: Id -> RM Id rewriteId v = do     !is_tagged <- isTagged v-    if is_tagged then return $! setIdTagSig v (TagSig TagProper)+    if is_tagged then return $! setIdTagSig v (TagVal TagEPT)                  else return v  rewriteExpr :: GenStgExpr 'InferTaggedBinders -> RM (GenStgExpr 'CodeGen)
GHC/Stg/EnforceEpt/TagSig.hs view
@@ -17,65 +17,119 @@ import GHC.Utils.Outputable import GHC.Utils.Binary import GHC.Utils.Panic.Plain-import Data.Coerce  -- | Information to be exposed in interface files which is produced -- by the stg2stg passes. type StgCgInfos = NameEnv TagSig -newtype TagSig  -- The signature for each binding, this is a newtype as we might-                -- want to track more information in the future.-  = TagSig TagInfo+-- Note [TagSig and TagInfo]+-- ~~~~~~~~~~~~~~~~~~~~~~~~~+-- 'TagSig' describes a *binding*; 'TagInfo' describes a *runtime value*.+--+-- A binding denotes either a value or a function:+--+--   * 'TagVal' i   — the binding holds a value whose runtime shape is 'i'.+--                    'i' covers thunks (TagDunno), evaluated/tagged heap+--                    pointers (TagEPT), unboxed tuples (TagTuple), and+--                    bottoming computations (TagBottoming).+--+--   * 'TagFun' i   — the binding is a function or join point. A function+--                    closure is always EPT. 'i' describes what a+--                    *saturated call* returns.+--                    See Note [TagInfo of functions] in GHC.Stg.EnforceEpt.+--+-- This split keeps 'combineAltInfo' at the value level: case alternatives+-- combine 'TagInfo', not 'TagSig'. An alternative that returns a function+-- closure gets 'TagEPT' (closure pointer is tagged) with no tracked return+-- info — the return info only matters once the function is applied, and at+-- that point it's looked up from the binding's 'TagSig' via+-- 'lookupReturnInfo'.++-- | The signature attached to a binding.+data TagSig+  = TagVal TagInfo        -- ^ A value binding (thunk, constructor, etc.)+  | TagFun TagInfo        -- ^ A function/join-point binding; carries the+                          -- TagInfo of saturated-call return values.+                          -- See Note [TagInfo of functions].   deriving (Eq) +-- Note [TagInfo lattice]+-- ~~~~~~~~~~~~~~~~~~~~~~+-- The TagInfo lattice describes what we know about whether a runtime value+-- is properly tagged (pointer tag bits set for heap pointers):+--+--   TagBottoming (bottom) ⊑ {TagEPT, TagTuple _} ⊑ TagDunno (top)+--+-- TagBottoming is the identity element for 'combineAltInfo': it is used as+-- the initial signature in fixpoint loops and for dead-end (bottoming)+-- computations, since their return value can be given any tag — they never+-- actually return.++-- | What we know about a runtime value. data TagInfo-  = TagDunno            -- We don't know anything about the tag.-  | TagTuple [TagInfo]  -- Represents a function/thunk which when evaluated-                        -- will return a Unboxed tuple whos components have-                        -- the given TagInfos.-  | TagProper           -- Heap pointer to properly-tagged value-  | TagTagged           -- Bottom of the domain.+  = TagDunno            -- ^ We don't know anything about the tag.+  | TagTuple [TagInfo]  -- ^ An unboxed tuple with taginfo for each element.+  | TagEPT              -- ^ An evaluated and properly tagged value.+                        -- See Note [Evaluated and Properly Tagged].+  | TagBottoming        -- ^ Bottom of the domain.+                        -- See Note [Bottom functions are TagBottoming] in GHC.Stg.EnforceEpt.   deriving (Eq)  instance Outputable TagInfo where-  ppr TagTagged      = text "TagTagged"-  ppr TagDunno       = text "TagDunno"-  ppr TagProper      = text "TagProper"-  ppr (TagTuple tis) = text "TagTuple" <> brackets (pprWithCommas ppr tis)+  ppr TagBottoming      = text "TagBottoming"+  ppr TagDunno          = text "TagDunno"+  ppr TagEPT            = text "TagEPT"+  ppr (TagTuple tis)    = text "TagTuple" <> brackets (pprWithCommas ppr tis)  instance Binary TagInfo where-  put_ bh TagDunno  = putByte bh 1+  put_ bh TagDunno        = putByte bh 1   put_ bh (TagTuple flds) = putByte bh 2 >> put_ bh flds-  put_ bh TagProper = putByte bh 3-  put_ bh TagTagged = putByte bh 4+  put_ bh TagEPT          = putByte bh 3+  put_ bh TagBottoming    = putByte bh 4    get bh = do tag <- getByte bh               case tag of 1 -> return TagDunno                           2 -> TagTuple <$> get bh-                          3 -> return TagProper-                          4 -> return TagTagged+                          3 -> return TagEPT+                          4 -> return TagBottoming                           _ -> panic ("get TagInfo " ++ show tag)  instance Outputable TagSig where-  ppr (TagSig ti) = char '<' <> ppr ti <> char '>'+  ppr (TagVal ti) = char '<' <> text "TagVal" <> brackets (ppr ti) <> char '>'+  ppr (TagFun ti) = char '<' <> text "TagFun" <> brackets (ppr ti) <> char '>'+ instance OutputableBndr (Id,TagSig) where   pprInfixOcc  = ppr   pprPrefixOcc = ppr  instance Binary TagSig where-  put_ bh (TagSig sig) = put_ bh sig-  get bh = pure TagSig <*> get bh+  put_ bh (TagVal ti) = putByte bh 1 >> put_ bh ti+  put_ bh (TagFun ti) = putByte bh 2 >> put_ bh ti+  get bh = do tag <- getByte bh+              case tag of 1 -> TagVal <$> get bh+                          2 -> TagFun <$> get bh+                          _ -> panic ("get TagSig " ++ show tag) +-- | Is the given binding known to be properly tagged (or irrelevant, as for+-- unboxed values and bottoming computations)? isTaggedSig :: TagSig -> Bool-isTaggedSig (TagSig TagProper) = True-isTaggedSig (TagSig TagTagged) = True-isTaggedSig _ = False+isTaggedSig (TagFun _)  = True+isTaggedSig (TagVal ti) = isTaggedInfo ti +-- | Is the given value-level tag known to be properly tagged?+-- NB: unboxed tuples are *not* treated as tagged here; they are handled+-- specially by the rewriter. See Note [Constructor TagSigs]+isTaggedInfo :: TagInfo -> Bool+isTaggedInfo TagEPT       = True+isTaggedInfo TagBottoming = True+isTaggedInfo _            = False+ seqTagSig :: TagSig -> ()-seqTagSig = coerce seqTagInfo+seqTagSig (TagVal ti) = seqTagInfo ti+seqTagSig (TagFun ti) = seqTagInfo ti  seqTagInfo :: TagInfo -> ()-seqTagInfo TagTagged      = ()+seqTagInfo TagBottoming   = () seqTagInfo TagDunno       = ()-seqTagInfo TagProper      = ()-seqTagInfo (TagTuple tis) = foldl' (\_unit sig -> seqTagSig (coerce sig)) () tis+seqTagInfo TagEPT         = ()+seqTagInfo (TagTuple tis) = foldl' (\_unit info -> seqTagInfo info) () tis
GHC/Stg/EnforceEpt/Types.hs view
@@ -13,7 +13,7 @@ import GHC.Prelude  import GHC.Core.DataCon-import GHC.Core.Type (isUnliftedType)+import GHC.Core.Type (isUnliftedType, definitelyUnliftedType) import GHC.Types.Id import GHC.Stg.Syntax import GHC.Stg.EnforceEpt.TagSig as TagSig@@ -23,6 +23,7 @@ import GHC.Utils.Panic  import GHC.StgToCmm.Types+import GHC.StgToCmm.Closure (importedIdLFInfo)  {- ********************************************************************* *                                                                      *@@ -36,15 +37,23 @@ type InferStgRhs        = GenStgRhs        'InferTaggedBinders type InferStgAlt        = GenStgAlt        'InferTaggedBinders +-- | Combine TagInfo from the alternatives of a case expression.+-- Note that this operates at the value level: case alternatives return+-- values. See Note [TagSig and TagInfo]. combineAltInfo :: TagInfo -> TagInfo -> TagInfo-combineAltInfo TagDunno         _              = TagDunno-combineAltInfo _                TagDunno       = TagDunno-combineAltInfo (TagTuple {})    TagProper      = TagDunno  -- This can happen with rep-polymorphic result, see #26107-combineAltInfo TagProper       (TagTuple {})   = TagDunno  -- This can happen with rep-polymorphic result, see #26107-combineAltInfo TagProper        TagProper      = TagProper+combineAltInfo TagBottoming    ti              = ti+combineAltInfo ti              TagBottoming    = ti+combineAltInfo TagDunno        TagDunno        = TagDunno+combineAltInfo TagDunno        TagEPT          = TagDunno+combineAltInfo TagDunno        (TagTuple {})   = TagDunno+combineAltInfo TagEPT          TagDunno        = TagDunno+combineAltInfo (TagTuple {})   TagDunno        = TagDunno+combineAltInfo TagEPT          TagEPT          = TagEPT+-- TagEPT/TagTuple are incompatible (can arise with rep-polymorphic+-- results, see #26107); fall through to TagDunno.+combineAltInfo TagEPT          (TagTuple {})   = TagDunno+combineAltInfo (TagTuple {})   TagEPT          = TagDunno combineAltInfo (TagTuple is1)  (TagTuple is2)  = TagTuple (zipWithEqual combineAltInfo is1 is2)-combineAltInfo (TagTagged)      ti             = ti-combineAltInfo ti               TagTagged      = ti  type TagSigEnv = IdEnv TagSig data TagEnv p = TE { te_env :: TagSigEnv@@ -76,70 +85,82 @@  noSig :: TagEnv p -> BinderP p -> (Id, TagSig) noSig env bndr-  | isUnliftedType (idType var) = (var, TagSig TagProper)-  | otherwise = (var, TagSig TagDunno)+  | isUnliftedType (idType var) = (var, TagVal TagEPT)+  | otherwise = (var, TagVal TagDunno)   where     var = getBinderId env bndr --- | Look up a sig in the given env-lookupSig :: TagEnv p -> Id -> Maybe TagSig-lookupSig env fun = lookupVarEnv (te_env env) fun+-- | Look up the return-value tag of a function for saturated call analysis.+-- Returns 'Just retInfo' if the function binding has a 'TagFun' signature,+-- 'Nothing' otherwise.+lookupReturnInfo :: TagEnv p -> Id -> Maybe TagInfo+lookupReturnInfo env fun = case lookupVarEnv (te_env env) fun of+  Just (TagFun ret_info) -> Just ret_info+  Just (TagVal _)        -> Nothing+  Nothing                -> Nothing --- | Look up a sig in the env or derive it from information--- in the arg itself.-lookupInfo :: TagEnv p -> StgArg -> TagInfo-lookupInfo env (StgVarArg var)+-- | Look up a value-level tag.+--+-- If the tag info is completely determined by Id info we use that tag.+-- If the tag info is dependent on the analysis/call site use the passed TagSig.+-- If the passed TagSig is Nothing we fall back to safe tag info based on id properties.+argTagInfo :: Bool -> (Maybe TagSig) -> StgArg -> TagInfo+{-# INLINE argTagInfo #-} -- Specialize for the call site.+argTagInfo _for_bytecode _env_sig (StgLitArg{}) = TagEPT+argTagInfo for_bytecode env_sig (StgVarArg var)   -- Nullary data constructors like True, False   | Just dc <- isDataConWorkId_maybe var   , isNullaryRepDataCon dc   , not for_bytecode-  = TagProper+  = TagEPT -  | isUnliftedType (idType var)-  = TagProper+  -- NB: v might be the Id of a representation-polymorphic join point,+  -- so we shouldn't use isUnliftedType here. See T22212.+  | definitelyUnliftedType (idType var)+  = TagEPT -  -- Variables in the environment.-  | Just (TagSig info) <- lookupVarEnv (te_env env) var-  = info+  -- Variables in the environment. A function binding flattens to TagEPT+  -- since a function closure pointer is properly tagged; its return info+  -- is not relevant when the function is used as a value.+  | Just sig <- env_sig+  = case sig of+      TagVal info -> info+      TagFun _    -> TagEPT -  | Just lf_info <- idLFInfo_maybe var-  , not for_bytecode-  =   case lf_info of+-- Always save defaults.+  | lf_info <- importedIdLFInfo var -- will make up LFInfo if not present.+  = if for_bytecode+    then TagDunno -- See Note [EPT enforcement for interpreted code] in GHC.Stg.EnforceEpt, point b)+    else+        case lf_info of           -- Function, tagged (with arity)           LFReEntrant {}-              -> TagProper+              -> TagEPT           -- Thunks need to be entered.           LFThunk {}               -> TagDunno           -- Constructors, already tagged.           LFCon {}-              -> TagProper+              -> TagEPT           LFUnknown {}               -> TagDunno           LFUnlifted {}-              -> TagProper+              -> TagEPT           -- Shouldn't be possible. I don't think we can export letNoEscapes           LFLetNoEscape {} -> panic "LFLetNoEscape exported" -  | otherwise-  = TagDunno-  where-    for_bytecode = te_bytecode env--lookupInfo _ (StgLitArg {})-  = TagProper+-- | Get tag info using the environment.+lookupInfo :: TagEnv p -> StgArg -> TagInfo+lookupInfo env arg@(StgVarArg var) =+    let env_sig = (lookupVarEnv (te_env env) var)+    in  argTagInfo (te_bytecode env) env_sig arg+lookupInfo _env (StgLitArg{}) = TagEPT  isDunnoSig :: TagSig -> Bool-isDunnoSig (TagSig TagDunno) = True-isDunnoSig (TagSig TagProper) = False-isDunnoSig (TagSig TagTuple{}) = False-isDunnoSig (TagSig TagTagged{}) = False--isTaggedInfo :: TagInfo -> Bool-isTaggedInfo TagProper = True-isTaggedInfo TagTagged = True-isTaggedInfo _         = False+isDunnoSig (TagVal TagDunno) = True+isDunnoSig _                 = False +-- | Extend the tag environment. extendSigEnv :: TagEnv p -> [(Id,TagSig)] -> TagEnv p extendSigEnv env@(TE { te_env = sig_env }) bndrs   = env { te_env = extendVarEnvList sig_env bndrs }
GHC/StgToByteCode.hs view
@@ -1122,7 +1122,7 @@         -- 'Simple' tuples with at most one non-void component,         -- like (# Word# #) or (# Int#, State# RealWorld #) do not have a         -- tuple return frame. This is because (# foo #) and (# foo, Void# #)-        -- have the same runtime rep. We have more efficient specialized+        -- have the same runtime rep. We have more efficient small         -- return frames for the situations with one non-void element.          non_void_arg_reps = typeArgReps platform bndr_ty@@ -1140,10 +1140,19 @@         -- When an alt is entered, it assumes the returned value is         -- on top of the itbl; see Note [Return convention for non-tuple values]         -- for details.+        -- Whether this tuple return uses a small stg_ctoi_tN frame+        -- (no old_spill slot, no TSO access) instead of the generic+        -- stg_ctoi_t frame.+        small_tuple_frame :: Bool+        small_tuple_frame =+          ubx_tuple_frame && nativeCallStackSpillSize call_info <= mAX_SMALL_TUPLE_CTOI+         ctoi_frame_header_w :: WordOff         ctoi_frame_header_w-          | ubx_tuple_frame =+          | small_tuple_frame =               if profiling then 5 else 4+          | ubx_tuple_frame =+              if profiling then 6 else 5           | otherwise = 2          -- The size of the ret_*_info frame header, whose frame returns the@@ -1289,10 +1298,16 @@         -- case-of-case expressions, which is the only time we can be compiling a         -- case expression with s /= 0. -        -- unboxed tuples get two more words, the second is a pointer (tuple_bco)+        -- unboxed tuples get extra words in the ctoi frame after the+        -- info pointer and cont_BCO:+        --   call_info, tuple_BCO, [old_spill], [CCCS]+        -- tuple_BCO at position 1 is a pointer.+        -- Small frames (stg_ctoi_tN) omit the old_spill slot.         (extra_pointers, extra_slots)-           | ubx_tuple_frame && profiling = ([1], 3) -- call_info, tuple_BCO, CCCS-           | ubx_tuple_frame              = ([1], 2) -- call_info, tuple_BCO+           | small_tuple_frame && profiling = ([1], 3) -- call_info, tuple_BCO, CCCS+           | small_tuple_frame              = ([1], 2) -- call_info, tuple_BCO+           | ubx_tuple_frame && profiling = ([1], 4) -- call_info, tuple_BCO, old_spill, CCCS+           | ubx_tuple_frame              = ([1], 3) -- call_info, tuple_BCO, old_spill            | otherwise                    = ([], 0)          bitmap_size :: WordOff@@ -1530,14 +1545,12 @@                list is active. Bit 1 for the                second register in the list and so on. -  - bit 24-31: Unsigned byte indicating the stack offset+  - bit 24+:   Unsigned value indicating the stack offset                of the continuation in words. For tuple returns                this is the number of words returned on the                stack. For primcalls this field is unused, since                we don't jump to a continuation. -The upper 32 bits on 64 bit platforms are currently unused.- If a register is smaller than a word on the stack (for example a single precision float on a 64 bit system), then the stack slot is padded to a whole word.@@ -1546,8 +1559,8 @@      If a tuple is returned in three registers and an additional two     words on the stack, then three bits in the register bitmap-    (bits 0-23) would be set. And bit 24-31 would be-    00000010 (two in binary).+    (bits 0-23) would be set. And the stack offset (bits 24+) would+    encode the value two.      The values on the stack before a call to POP_ARG_REGS would     be as follows:@@ -1575,7 +1588,7 @@      At this point all the arguments are in place and we are ready     to jump to the continuation, the location (offset from Sp) of-    which is found by inspecting the value of bits 24-31. In this+    which is found by inspecting the value of bits 24+. In this     case the offset is two words.  On x86_64, the double precision (Dn) and single precision@@ -1729,9 +1742,11 @@      * tuple_BCO: see below    The interpreter pushes these onto the stack when the PUSH_ALTS_TUPLE-  instruction is executed, followed by stg_ctoi_tN_info, with N depending-  on the number of stack words used by the tuple in the GHC native calling-  convention. N is derived from call_info.+  instruction is executed, followed by stg_ctoi_t_info. It also saves+  the old ctoi_tuple_spill_words value from the TSO in the frame and sets+  the TSO field to the number of stack words used by the tuple in the+  GHC native calling convention. This spill count is derived from+  call_info.    For example if we expect a tuple with three words on the stack, the stack   looks as follows after PUSH_ALTS_TUPLE:@@ -1742,12 +1757,13 @@       cont_free_var_2       ...       cont_free_var_n+      old_spill       call_info       tuple_BCO       cont_BCO-      stg_ctoi_t3_info <- Sp+      stg_ctoi_t_info  <- Sp -  If the tuple is returned by object code, stg_ctoi_t3 will deal with+  If the tuple is returned by object code, stg_ctoi_t will deal with   adjusting the stack pointer and converting the tuple to the bytecode   calling convention. See Note [GHCi unboxed tuples stack spills] for more   details.
GHC/StgToCmm/Bind.hs view
@@ -280,7 +280,7 @@   = do     profile <- getProfile     check_tags <- stgToCmmDoTagCheck <$> getStgToCmmConfig-    use_std_ap_thunk <- stgToCmmTickyAP <$> getStgToCmmConfig+    use_std_ap_thunk <- stgToCmmUseStdApThunk <$> getStgToCmmConfig     mkRhsClosure profile use_std_ap_thunk check_tags id cc (nonVoidIds (dVarSetElems fvs)) upd_flag args body  ------------------------------------------------------------------------@@ -587,9 +587,8 @@                 -- ticky after heap check to avoid double counting                 ; tickyEnterFun cl_info                 ; enterCostCentreFun cc-                    (CmmMachOp (mo_wordSub platform)-                         [ CmmReg (CmmLocal node) -- See [NodeReg clobbered with loopification]-                         , mkIntExpr platform (funTag platform cl_info) ])+                    (cmmUntag platform (CmmReg (CmmLocal node))) -- See [NodeReg clobbered with loopification]+                 ; fv_bindings <- mapM bind_fv fv_details                 -- Load free vars out of closure *after*                 -- heap check, to reduce live vars over check@@ -866,7 +865,7 @@   ; let profile  = stgToCmmProfile cfg   ; let platform = profilePlatform profile   ; bh <- newTemp (bWord platform)-  ; emitRtsCallGen [(bh,AddrHint)] newCAF_lbl+  ; emitRtsCallGen [(bh,AddrHint)] newCAF_lbl CmmMayReturn       [ (baseExpr platform,  AddrHint),         (CmmReg (CmmLocal node), AddrHint) ]       False
GHC/StgToCmm/Config.hs view
@@ -73,7 +73,7 @@   , stgToCmmAllowWordMul2Instr        :: !Bool   -- ^ Allowed to generate WordMul2 instruction   , stgToCmmAllowFMAInstr             :: FMASign -> Bool -- ^ Allowed to generate FMA instruction   , stgToCmmAllowIntWord64X2MinMax    :: !Bool   -- ^ Allowed to generate min/max instructions for Int64X2/Word64X2-  , stgToCmmTickyAP                   :: !Bool   -- ^ Disable use of precomputed standard thunks.+  , stgToCmmUseStdApThunk             :: !Bool   -- ^ Use precomputed standard AP thunks in the RTS.   , stgToCmmSaveFCallTargetToLocal    :: !Bool   -- ^ Save a foreign call target to a Cmm local, see                                                  -- Note [Saving foreign call target to local] for details   ------------------------------ SIMD flags ------------------------------------
GHC/StgToCmm/Utils.hs view
@@ -189,23 +189,27 @@ emitBarf :: String -> FCode () emitBarf msg = do   strLbl <- newStringCLit msg-  emitRtsCall rtsUnitId (fsLit "barf") [(CmmLit strLbl,AddrHint)] False+  emitRtsCallGen [] (mkCmmCodeLabel rtsUnitId (fsLit "sbarf"))+    CmmNeverReturns+    [(CmmLit strLbl, AddrHint)] False  emitRtsCall :: UnitId -> FastString -> [(CmmExpr,ForeignHint)] -> Bool -> FCode ()-emitRtsCall pkg fun = emitRtsCallGen [] (mkCmmCodeLabel pkg fun)+emitRtsCall pkg fun = emitRtsCallGen [] (mkCmmCodeLabel pkg fun) CmmMayReturn  emitRtsCallWithResult :: LocalReg -> ForeignHint -> UnitId -> FastString         -> [(CmmExpr,ForeignHint)] -> Bool -> FCode ()-emitRtsCallWithResult res hint pkg = emitRtsCallGen [(res,hint)] . mkCmmCodeLabel pkg+emitRtsCallWithResult res hint pkg =+  \fun -> emitRtsCallGen [(res,hint)] (mkCmmCodeLabel pkg fun) CmmMayReturn  -- Make a call to an RTS C procedure emitRtsCallGen    :: [(LocalReg,ForeignHint)]    -> CLabel+   -> CmmReturnInfo    -> [(CmmExpr,ForeignHint)]    -> Bool -- True <=> CmmSafe call    -> FCode ()-emitRtsCallGen res lbl args safe+emitRtsCallGen res lbl ret_info args safe   = do { platform <- getPlatform        ; updfr_off <- getUpdFrameOff        ; let (caller_save, caller_load) = callerSaveVolatileRegs platform@@ -217,7 +221,7 @@       if safe then         emit =<< mkCmmCall fun_expr res' args' updfr_off       else do-        let conv = ForeignConvention CCallConv arg_hints res_hints CmmMayReturn+        let conv = ForeignConvention CCallConv arg_hints res_hints ret_info         emit $ mkUnsafeCall (ForeignTarget fun_expr conv) res' args'     (args', arg_hints) = unzip args     (res',  res_hints) = unzip res
GHC/StgToJS/Apply.hs view
@@ -185,7 +185,7 @@       as'      <- concatMapM genArg args       ei       <- varForEntryId i       let ra = mconcat . reverse $-                 zipWith (\r a -> toJExpr r |= a) [R1 ..] as'+                 zipWith (\r a -> toJExpr r |= a) regsFromR1 as'       p <- pushLneFrame n ctx       a <- adjSp 1 -- for the header (which will only be written when the thread is suspended)       return (ra <> p <> a <> returnS ei, ExprCont)@@ -464,42 +464,31 @@ specTagExpr :: ApplySpec -> JStgExpr specTagExpr = toJExpr . specTag --- | Build arrays to quickly lookup apply functions+-- | Build functions to quickly lookup apply functions -----  h$apply[r << 8 | n] = function application for r regs, n args---  h$paps[r]           = partial application for r registers (number of args is in the object)+--  h$apply(r << 8 | n) = function application for r regs, n args+--  h$paps(r)           = partial application for r registers (number of args is in the object) mkApplyArr :: JSM JStgStat mkApplyArr =-  do mk_ap_gens  <- jFor (|= zero_) (.<. Int 65536) preIncrS-                    \j -> hdApply .! j |= hdApGen-     mk_pap_gens <- jFor (|= zero_) (.<. Int 128) preIncrS-                    \j -> hdPaps .! j |=  hdPapGen+  do paps_fun <- jFunction (name hdPapsStr) \(MkSolo i) -> pure $ SwitchStat i (map case_pap specPap) (returnS hdPapGen)+     apply_fun <- jFunction (name hdApplyStr) \(MkSolo i) -> pure $ SwitchStat i (mapMaybe' case_apply applySpec) (returnS hdApGen)      return $ mconcat-       [ name hdApplyStr ||= toJExpr (JList [])-       , name hdPapsStr  ||= toJExpr (JList [])-       , ApplStat (hdInitStatic .^ "push")-         [ jLam' $-           mconcat-           [ mk_ap_gens-           , mk_pap_gens-           , mconcat (map assignSpec applySpec)-           , mconcat (map assignPap specPap)-           ]-         ]+       [ paps_fun+       , apply_fun        ]   where-    assignSpec :: ApplySpec -> JStgStat-    assignSpec spec = case specConv spec of+    case_apply :: ApplySpec -> Maybe (JStgExpr,JStgStat)+    case_apply spec = case specConv spec of       -- both fast/slow (regs/stack) specialized apply functions have the same       -- tags. We store the stack ones in the array because they are used as       -- continuation stack frames.-      StackConv -> hdApply .! specTagExpr spec |= specApplyExpr spec-      RegsConv  -> mempty+      StackConv -> Just (specTagExpr spec, returnS (specApplyExpr spec))+      RegsConv  -> Nothing      hdPap_ = unpackFS hdPapStr_ -    assignPap :: Int -> JStgStat-    assignPap p = hdPaps .! toJExpr p |= global (mkFastString (hdPap_ ++ show p))+    case_pap :: Int -> (JStgExpr, JStgStat)+    case_pap p = (toJExpr p,  returnS $ global (mkFastString (hdPap_ ++ show p)))  -- | Push a continuation on the stack --@@ -619,7 +608,7 @@                          -- compute new tag with consumed register values and args removed                          , newTag |= ((given_regs-needed_regs).<<.8) .|. (given_args - needed_args)                          -- find application function for the remaining regs/args-                         , newAp |= hdApply .! newTag+                         , newAp |= ApplExpr hdApply [newTag]                          , traceRts cfg (jString "h$ap_gen: next: " + (newAp .^ "n"))                           -- Drop used registers from the stack.@@ -643,7 +632,7 @@                          -----------------------------                          [ traceRts cfg (jString "h$ap_gen: undersat")                          -- find PAP entry function corresponding to given_regs count-                         , p      |= hdPaps .! given_regs+                         , p      |= ApplExpr hdPaps [given_regs]                           -- build PAP payload: R1 + tag + given register values                          , newTag |= ((needed_regs-given_regs) .<<. 8) .|. (needed_args-given_args)@@ -716,7 +705,7 @@              do push_all_regs <- pushAllRegs tag                 return $ mconcat $                   [ push_all_regs-                  , ap |= hdApply .! tag+                  , ap |= ApplExpr hdApply [tag]                   , ifS (ap .===. hdApGen)                     ((sp |= sp + 2) <> (stack .! (sp-1) |= tag))                     (sp |= sp + 1)@@ -750,7 +739,7 @@                 , traceRts s (jString "h$ap_gen_fast: oversat " + sp)                 , push_args                 , newTag |= ((myRegs-( arity.>>.8)).<<.8).|.myAr-ar-                , newAp |= hdApply .! newTag+                , newAp |= ApplExpr hdApply [newTag]                 , ifS (newAp .===. hdApGen)                   ((sp |= sp + 2) <> (stack .! (sp - 1) |= newTag))                   (sp |= sp + 1)@@ -761,7 +750,7 @@                -- else                 [traceRts s (jString "h$ap_gen_fast: undersat: " + myRegs + jString " " + tag)                 , jwhenS (tag .!=. 0) $ mconcat-                  [ p |= hdPaps .! myRegs+                  [ p |= ApplExpr hdPaps [myRegs]                   , dat |= toJExpr [r1, ((arity .>>. 8)-myRegs)*256+ar-myAr]                   , get_regs                   , r1 |= initClosure s p dat jCurrentCCS@@ -773,14 +762,24 @@     pushAllRegs :: JStgExpr -> JSM JStgStat     pushAllRegs tag =       jVar \regs ->-             return $ mconcat $-             [ regs |= tag .>>. 8-             , sp |= sp + regs-             , SwitchStat regs (map pushReg [65,64..2]) mempty-             ]-      where-        pushReg :: Int -> (JStgExpr, JStgStat)-        pushReg r = (toJExpr (r-1),  stack .! (sp - toJExpr (r - 2)) |= jsReg r)+             let max_low_reg = regNumber maxLowReg+                 low_regs = [max_low_reg, max_low_reg-1..2] -- R1 isn't used for arguments+                 pushReg :: Int -> (JStgExpr, JStgStat)+                 pushReg r = (toJExpr r,  stack .! (sp - toJExpr (r - 2)) |= jsReg r)+             in return $ mconcat $+                  [ regs |= tag .>>. 8+                  , sp |= sp + regs+                    -- increment the number of regs by 1, so that it matches register+                    -- numbers (R1 is not used for args)+                  , postIncrS regs+                    -- copy high registers with a loop+                  , WhileStat False (regs .>. toJExpr max_low_reg) $ mconcat+                      -- rN stored in stack[sp - N - 2] so that r2 is stored in stack[sp], etc.+                      [ stack .! (sp - regs - 2) |= highReg_expr regs+                      , postDecrS regs+                      ]+                  , SwitchStat regs (map pushReg low_regs) mempty+                  ]      pushArgs :: JStgExpr -> JStgExpr -> JSM JStgStat     pushArgs start end =@@ -906,7 +905,7 @@              [ rs |= (arity .>>. 8)              , loadRegs rs              , sp |= sp - rs-             , newAp |= (hdApply .! ((toJExpr nargs-arity0).|.((toJExpr nvars-rs).<<.8)))+             , newAp |= ApplExpr hdApply [(toJExpr nargs-arity0).|.((toJExpr nvars-rs).<<.8)]              , stack .! sp |= newAp              , profStat s pushRestoreCCS              , traceRts s (toJExpr (fun_name <> ": new stack frame: ") + (newAp .^ "n"))@@ -989,7 +988,7 @@                               + rsRemain)                 , saveRegs rs                 , sp |= sp + rsRemain + 1-                , stack .! sp |= hdApply .! ((rsRemain.<<.8).|. (toJExpr nargs - mask8 arity))+                , stack .! sp |= ApplExpr hdApply [(rsRemain.<<.8).|. (toJExpr nargs - mask8 arity)]                 , profStat s pushRestoreCCS                 , returnS c                 ]@@ -1238,14 +1237,30 @@              , profStat s (enterCostCentreFun currentCCS)              , extra |= (funOrPapArity c (Just f) .>>. 8) - toJExpr r              , traceRts s (toJExpr (funcName <> ": pap extra args moving: ") + extra)-             , moveBy extra+             , case r of+                0 -> mempty -- in pap_0 we don't shift any register+                _ -> moveBy extra              , loadOwnArgs d              , r1 |= c              , returnS f              ]-    moveBy extra = SwitchStat extra-                   (reverse $ map moveCase [1..maxReg-r-1]) mempty-    moveCase m = (toJExpr m, jsReg (m+r+1) |= jsReg (m+1))+    moveBy extra =+      let max_low_reg = regNumber maxLowReg+          low_regs = [max_low_reg, max_low_reg-1..2] -- R1 isn't used for arguments+          move_case m = (toJExpr m, jsReg (m+r) |= jsReg m)+      in mconcat+          [ -- increment the number of args by 1, so that it matches register+            -- numbers (R1 is not used for args)+            postIncrS extra+            -- copy high registers with a loop+          ,  WhileStat False (extra .>. toJExpr max_low_reg) $ mconcat+              [ highReg_expr (extra + toJExpr r) |= highReg_expr extra+              , postDecrS extra+              ]+            -- then copy low registers with a case+          , SwitchStat extra (map move_case low_regs) mempty+          ]+     loadOwnArgs d = mconcat $ map (\r ->         jsReg (r+1) |= dField d (r+2)) [1..r]     dField d n = SelExpr d (name . mkFastString $ ('d':show (n-1)))@@ -1274,7 +1289,9 @@                 (jString "h$pap_gen: expected function or pap")               , profStat cfg (enterCostCentreFun currentCCS)               , traceRts cfg (jString "h$pap_gen: generic pap extra args moving: " + or)+                -- shift newly applied arguments into appropriate registers               , appS hdMoveRegs2 [or, r]+                -- load stored arguments into lowest argument registers (i.e. starting from R2)               , loadOwnArgs d r               , r1 |= c               , returnS f@@ -1285,9 +1302,22 @@     funcIdent = name funcName     funcName = hdPapGenStr     loadOwnArgs d r =-      let prop n = d .^ ("d" <> mkFastString (show $ n+1))-          loadOwnArg n = (toJExpr n, jsReg (n+1) |= prop n)-      in  SwitchStat r (map loadOwnArg [127,126..1]) mempty+      let prop n = d .^ (mkFastString ("d" ++ show n))+          loadOwnArg n = (toJExpr n, jsReg n |= prop n)+          max_low_reg = regNumber maxLowReg+          low_regs = [max_low_reg, max_low_reg-1..2] -- R1 isn't used for arguments+      in  mconcat+            [ -- increment the number of args by 1, so that it matches register+              -- numbers (R1 is not used for args) and PAP fields (starting from d2)+              postIncrS r+              -- copy high registers with a loop+            ,  WhileStat False (r .>. toJExpr max_low_reg) $ mconcat+                [ highReg_expr r |= (d .! (jString (fsLit "d") + r))+                , postDecrS r+                ]+              -- then copy low registers with a case.+            , SwitchStat r (map loadOwnArg low_regs) mempty+            ]  -- general utilities -- move the first n registers, starting at R2, m places up (do not use with negative m)@@ -1301,7 +1331,7 @@     switchCase n m = (toJExpr $                       (n `Bits.shiftL` 8) Bits..|. m                      , mconcat (map (`moveRegFast` m) [n+1,n..2])-                       <> BreakStat Nothing {-[j| break; |]-})+                       <> BreakStat Nothing)     moveRegFast n m = jsReg (n+m) |= jsReg n     -- fallback     defaultCase n m =
GHC/StgToJS/Expr.hs view
@@ -312,7 +312,7 @@   -- load arguments into local variables   la <- do     args' <- concatMapM genIdArgI args-    return (declAssignAll args' (fmap toJExpr [startReg..]))+    return (declAssignAll args' (jsRegsFrom startReg))    -- assert that arguments have valid runtime reps   lav <- verifyRuntimeReps args@@ -665,7 +665,7 @@   | otherwise = do       rj       <- genRet ctx bnd at alts l       let ctx' = ctxSetTop bnd-                  $ ctxSetTarget (assocIdExprs bnd (map toJExpr [R1 ..]))+                  $ ctxSetTarget (assocIdExprs bnd jsRegsFromR1)                   $ ctx       (ej, _r) <- genExpr ctx' e       return (rj <> ej, ExprCont)@@ -730,7 +730,7 @@      fun free = resetSlots $ do       decs          <- declVarsForId e-      load          <- flip assignAll (map toJExpr [R1 ..]) . map toJExpr <$> identsForId e+      load          <- flip assignAll jsRegsFromR1 . map toJExpr <$> identsForId e       loadv         <- verifyRuntimeReps [e]       ras           <- loadRetArgs free       rasv          <- verifyRuntimeReps (map (\(x,_,_)->x) free)
GHC/StgToJS/Regs.hs view
@@ -1,4 +1,5 @@ {-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE PatternSynonyms #-}  module GHC.StgToJS.Regs   ( StgReg (..)@@ -6,17 +7,25 @@   , sp   , stack   , r1, r2, r3, r4+  , pattern R1, pattern R2, pattern R3, pattern R4   , regsFromR1   , regsFromR2+  , regsFromTo+  , jsRegsFrom   , jsRegsFromR1   , jsRegsFromR2   , StgRet (..)-  , jsRegToInt-  , intToJSReg+  , regNumber   , jsReg+  , highReg+  , highReg_expr   , maxReg+  , maxLowReg   , minReg+  , minHighReg   , lowRegs+  , lowRegsCount+  , lowRegsIdents   , retRegs   , register   , foreignRegister@@ -32,6 +41,7 @@ import GHC.StgToJS.Symbols  import GHC.Data.FastString+import GHC.Utils.Panic.Plain  import Data.Array import qualified Data.ByteString.Char8 as BSC@@ -39,27 +49,16 @@ import Data.Semigroup ((<>))  -- | General purpose "registers"------ The JS backend arbitrarily supports 128 registers-data StgReg-  = R1  | R2  | R3  | R4  | R5  | R6  | R7  | R8-  | R9  | R10 | R11 | R12 | R13 | R14 | R15 | R16-  | R17 | R18 | R19 | R20 | R21 | R22 | R23 | R24-  | R25 | R26 | R27 | R28 | R29 | R30 | R31 | R32-  | R33 | R34 | R35 | R36 | R37 | R38 | R39 | R40-  | R41 | R42 | R43 | R44 | R45 | R46 | R47 | R48-  | R49 | R50 | R51 | R52 | R53 | R54 | R55 | R56-  | R57 | R58 | R59 | R60 | R61 | R62 | R63 | R64-  | R65 | R66 | R67 | R68 | R69 | R70 | R71 | R72-  | R73 | R74 | R75 | R76 | R77 | R78 | R79 | R80-  | R81 | R82 | R83 | R84 | R85 | R86 | R87 | R88-  | R89 | R90 | R91 | R92 | R93 | R94 | R95 | R96-  | R97  | R98  | R99  | R100 | R101 | R102 | R103 | R104-  | R105 | R106 | R107 | R108 | R109 | R110 | R111 | R112-  | R113 | R114 | R115 | R116 | R117 | R118 | R119 | R120-  | R121 | R122 | R123 | R124 | R125 | R126 | R127 | R128-  deriving (Eq, Ord, Show, Enum, Bounded, Ix)+newtype StgReg+  = StgReg Int+  deriving (Eq,Ord,Ix) +pattern R1, R2, R3, R4 :: StgReg+pattern R1 = StgReg 0+pattern R2 = StgReg 1+pattern R3 = StgReg 2+pattern R4 = StgReg 3+ -- | Stack registers data Special   = Stack@@ -78,7 +77,7 @@   toJExpr Sp     = hdStackPtr  instance ToJExpr StgReg where-  toJExpr r = registers ! r+  toJExpr r = register r  instance ToJExpr StgRet where   toJExpr r = rets ! r@@ -99,25 +98,42 @@ r3 = toJExpr R3 r4 = toJExpr R4 +-- | 1-indexed register number (R1 has index 1)+regNumber :: StgReg -> Int+regNumber (StgReg r) = r+1 -jsRegToInt :: StgReg -> Int-jsRegToInt = (+1) . fromEnum+-- | StgReg from 1-indexed number+regFromNumber :: Int -> StgReg+regFromNumber r = assert (r >= 1) $ StgReg (r-1) -intToJSReg :: Int -> StgReg-intToJSReg r = toEnum (r - 1)+regsFromTo :: StgReg -> StgReg -> [StgReg]+regsFromTo (StgReg x) (StgReg y) = map StgReg [x .. y] +-- | Register expression from its 1-indexed index jsReg :: Int -> JStgExpr-jsReg r = toJExpr (intToJSReg r)+jsReg r = toJExpr (regFromNumber r) -maxReg :: Int-maxReg = jsRegToInt maxBound+minReg :: StgReg+minReg = R1 -minReg :: Int-minReg = jsRegToInt minBound+maxReg :: StgReg+maxReg = regFromNumber maxBound +lowRegsCount :: Int+lowRegsCount = 31++maxLowReg :: StgReg+maxLowReg = regFromNumber lowRegsCount++-- | First register stored in h$regs array instead of having its own top-level+-- variable+minHighReg :: StgReg+minHighReg = case maxLowReg of+  StgReg r -> StgReg (r+1)+ -- | List of registers, starting from R1 regsFromR1 :: [StgReg]-regsFromR1 = enumFrom R1+regsFromR1 = regsFromTo R1 maxReg ++ repeat (panic "StgToJS: code requires too many registers")  -- | List of registers, starting from R2 regsFromR2 :: [StgReg]@@ -131,25 +147,36 @@ jsRegsFromR2 :: [JStgExpr] jsRegsFromR2 = tail jsRegsFromR1 +-- | List of registers, starting from given reg as JExpr+jsRegsFrom :: StgReg -> [JStgExpr]+jsRegsFrom (StgReg n) = drop n jsRegsFromR1++-- | High register+highReg :: Int -> JStgExpr+highReg r = assert (r >= regNumber minHighReg) $ IdxExpr hdRegs (toJExpr (r - regNumber minHighReg))++-- | High register indexing with a JS expression+highReg_expr :: JStgExpr -> JStgExpr+highReg_expr r = IdxExpr hdRegs (r - toJExpr (regNumber minHighReg))++ --------------------------------------------------- -- caches --------------------------------------------------- -lowRegs :: [Ident]-lowRegs = map reg_to_ident [R1 .. R31]-  where reg_to_ident = name . mkFastString . (unpackFS hdStr ++) . map toLower . show+lowRegs :: [StgReg]+lowRegs = regsFromTo minReg maxLowReg +lowRegsIdents :: [Ident]+lowRegsIdents = map reg_to_ident lowRegs+  where+    -- low regs are named h$r1, h$r2, etc.+    reg_to_ident r = name (mkFastString (unpackFS hdStr ++ "r" ++ show (regNumber r)))+ retRegs :: [Ident] retRegs = [name . mkFastStringByteString            $ hdB <> BSC.pack (map toLower $ show n) | n <- enumFrom Ret1] --- cache JExpr representing StgReg-registers :: Array StgReg JStgExpr-registers = listArray (minBound, maxBound) (map (global . identFS) lowRegs ++ map regN [R32 .. R128])-  where-    regN :: StgReg -> JStgExpr-    regN r = IdxExpr hdRegs (toJExpr (fromEnum r - 32))- -- cache JExpr representing StgRet rets :: Array StgRet JStgExpr rets = listArray (minBound, maxBound) (map retN (enumFrom Ret1))@@ -157,9 +184,22 @@     retN = global . mkFastString . (unpackFS hdStr ++) . map toLower . show  -- | Given a register, return the JS syntax object representing that register-register :: StgReg -> JStgExpr-register i = registers ! i---- | Given a register, return the JS syntax object representing that register foreignRegister :: StgRet -> JStgExpr foreignRegister i = rets ! i++-- | Given a register, return the JS syntax object representing that register+register :: StgReg -> JStgExpr+register i+  | i <= maxCachedReg = register_cache ! i -- Expressions of common registers are cached.+  | otherwise         = make_high_reg i    -- Expression of higher registers are made on the fly++maxCachedReg :: StgReg+maxCachedReg = regFromNumber 128++-- cache JExpr representing StgReg+register_cache :: Array StgReg JStgExpr+register_cache = listArray (minReg, maxCachedReg) (map (global . identFS) lowRegsIdents ++ map make_high_reg (regsFromTo minHighReg maxCachedReg))++-- | Make h$regs[XXX] expression for the register+make_high_reg :: StgReg -> JStgExpr+make_high_reg r = highReg (regNumber r)
GHC/StgToJS/Rts/Rts.hs view
@@ -54,7 +54,12 @@ -- | The garbageCollector resets registers and result variables. garbageCollector :: JSM JStgStat garbageCollector = jBlock-    [ jFunction' hdResetRegisters  (return $ mconcat $ map resetRegister [minBound..maxBound])+    [ jFunction' hdResetRegisters  $ return $ mconcat+        [ -- reset low registers explicitly+          mconcat (map resetRegister lowRegs)+          -- reset the whole h$regs array with h$regs.fill(null)+        , toStat $ ApplExpr (hdRegs .^ "fill") [null_]+        ]     , jFunction' hdResetResultVars (return $ mconcat $ map resetResultVar [minBound..maxBound])     ] @@ -249,7 +254,7 @@     loaders         <- loadRegs     return $       mconcat [ hdRegsStr ||= toJExpr (JList [])-              , mconcat (map declReg lowRegs)+              , mconcat (map declReg lowRegsIdents)               , getters_setters               , loaders               ]@@ -259,15 +264,15 @@ -- | JS payload to define getters and setters on the registers. regGettersSetters :: JSM JStgStat regGettersSetters =-  do setters <- jFunction (name hdGetRegStr) (\(MkSolo n) -> return $ SwitchStat n getRegCases mempty)-     getters <- jFunction (name hdSetRegStr) (\(n,v)      -> return $ SwitchStat n (setRegCases v) mempty)+  do getters <- jFunction (name hdGetRegStr) (\(MkSolo n) -> return $ SwitchStat n getRegCases (defaultGetRegCase n))+     setters <- jFunction (name hdSetRegStr) (\(n,v)      -> return $ SwitchStat n (setRegCases v) (defaultSetRegCase n v))      return $ setters <> getters   where-    getRegCases =-      map (\r -> (toJExpr (jsRegToInt r) , returnS (toJExpr r))) regsFromR1-    setRegCases :: JStgExpr -> [(JStgExpr,JStgStat)]-    setRegCases v =-      map (\r -> (toJExpr (jsRegToInt r), (toJExpr r |= toJExpr v) <> returnS undefined_)) regsFromR1+    getRegCases         = map (\r -> (toJExpr (regNumber r) , returnS (toJExpr r))) lowRegs+    defaultGetRegCase n = returnS (highReg_expr n)++    setRegCases v         = map (\r -> (toJExpr (regNumber r), (toJExpr r |= v) <> BreakStat Nothing)) lowRegs+    defaultSetRegCase n v = highReg_expr n |= v  -- | JS payload that defines the functions to load each register loadRegs :: JSM JStgStat
GHC/StgToJS/Rts/Types.hs view
@@ -69,12 +69,3 @@                 (tgt |= mask8 tag + 1)       -- else set to mask'd tag + 1               ]           ))--  ----------------------------------------------------------------------------------- Register utilities------------------------------------------------------------------------------------- | Perform the computation 'f', on the range of registers bounded by 'start'--- and 'end'.-withRegs :: StgReg -> StgReg -> (StgReg -> JStgStat) -> JStgStat-withRegs start end f = mconcat $ fmap f [start..end]
GHC/SysTools/Cpp.hs view
@@ -149,7 +149,7 @@         -- and BUILD is the same as our HOST.      let io_manager_defs =-          [ "-D__IO_MANAGER_WINIO__=1" | isWindows ] +++          [ "-D__IO_MANAGER_WINIO__=2" | isWindows ] ++           [ "-D__IO_MANAGER_MIO__=1"               ]      let sse_defs =
GHC/SysTools/Terminal.hs view
@@ -15,17 +15,9 @@ import qualified System.Win32 as Win32 #endif -import System.IO.Unsafe---- | Does the controlling terminal support ANSI color sequences?--- This memoized to avoid thread-safety issues in ncurses (see #17922).-stderrSupportsAnsiColors :: Bool-stderrSupportsAnsiColors = unsafePerformIO stderrSupportsAnsiColors'-{-# NOINLINE stderrSupportsAnsiColors #-}- -- | Check if ANSI escape sequences can be used to control color in stderr.-stderrSupportsAnsiColors' :: IO Bool-stderrSupportsAnsiColors' = do+stderrSupportsAnsiColors :: IO Bool+stderrSupportsAnsiColors = do #if !defined(mingw32_HOST_OS)   -- Equivalent of https://hackage.haskell.org/package/ansi-terminal/docs/System-Console-ANSI.html#v:hSupportsANSI   isTerminal <- hIsTerminalDevice stderr
GHC/Tc/Deriv/Generics.hs view
@@ -44,7 +44,6 @@  import GHC.Types.Name hiding ( varName ) import GHC.Types.Name.Reader-import GHC.Types.SourceText import GHC.Types.Fixity import GHC.Types.Basic import GHC.Types.SrcLoc@@ -379,7 +378,7 @@                max_fields = maximum $ 0 :| map dataConSourceArity datacons             inline1 f = L loc'' . InlineSig noAnn (L loc' f)-                     $ alwaysInlinePragma { inl_act = ActiveAfter NoSourceText 1 }+                     $ alwaysInlinePragma { inl_act = ActiveAfter 1 }          -- The topmost M1 (the datatype metadata) has the exact same type         -- across all cases of a from/to definition, and can be factored out
GHC/Tc/Errors.hs view
@@ -1147,8 +1147,14 @@     mkImplicitLiftingError :: ErrorItem -> TcRnMessage     mkImplicitLiftingError item =       case errorItemOrigin item of-        ImplicitLiftOrigin (HsImplicitLiftSplice bound used gre name) ->-          TcRnBadlyLevelled (LevelCheckSplice (getName name) gre) bound used (Just item) (cec_defer_type_errors ctxt)+        -- mgre is Nothing IFF LevelCheckReason is LevelCheckInstance+        ImplicitLiftOrigin (HsImplicitLiftSplice bound used (Just gre) loc_name) ->+          TcRnBadlyLevelled+            (LevelCheckSplice $ gre <$ unLoc loc_name)+            bound+            used+            (Just item)+            (cec_defer_type_errors ctxt)         _ -> pprPanic "mkImplicitLiftingError" (ppr item)  mkGivenErrorReporter :: Reporter@@ -1302,11 +1308,11 @@         ; case dest of            EvVarDest evar-             -> addTcEvBind ev_binds_var $ mkWantedEvBind evar EvNonCanonical err_tm+             -> addTcEvBind ev_binds_var $ mkWantedEvBind evar EvCanonical err_tm            HoleDest hole              -> do { -- See Note [Deferred errors for coercion holes]                      let co_var = coHoleCoVar hole-                   ; addTcEvBind ev_binds_var $ mkWantedEvBind co_var EvNonCanonical err_tm+                   ; addTcEvBind ev_binds_var $ mkWantedEvBind co_var EvCanonical err_tm                    ; fillCoercionHole hole (mkCoVarCo co_var) } } addDeferredBinding _ _ _ _ _ = return ()    -- Do not set any evidence for Given 
GHC/Tc/Errors/Ppr.hs view
@@ -1,6 +1,7 @@ {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE MonadComprehensions #-}+{-# LANGUAGE MultiWayIf #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE DataKinds #-}@@ -1517,9 +1518,9 @@       -> pprTcRnBadlyLevelled reason bind_lvls use_lvl lift_attempt     TcRnBadlyLevelledType name bind_lvls use_lvl       -> mkSimpleDecorated $-         text "Badly levelled type:" <+> ppr name <+>-         fsep [text "is bound at" <+> pprThBindLevel bind_lvls,-               text "but used at level" <+> ppr use_lvl]+         fsep [ text "Level error:"+              , ppr name <+> text "is used at level" <+> ppr use_lvl+              , text "but is bound at" <+> ppr_th_bind_level bind_lvls]     TcRnTyThingUsedWrong sort thing name       -> mkSimpleDecorated $          pprTyThingUsedWrong sort thing name@@ -1833,6 +1834,11 @@     TcRnUnusedName name reason       -> mkSimpleDecorated $          pprUnusedName name reason+    TcRnStaticFormWarning names+      -> mkSimpleDecorated $+         vcat [ hang (text "From GHC 10.0, static forms cannot mention nested let-bound variables")+                   2 (text "Offending variables:" <+> pprWithCommas ppr names)+              , text "Solution: move these free variables to top level" ]     TcRnQualifiedBinder rdr_name       -> mkSimpleDecorated $          text "Qualified name in binding position:" <+> ppr rdr_name@@ -2220,6 +2226,8 @@       -> ErrorWithoutFlag     TcRnStaticFormNotClosed{}       -> ErrorWithoutFlag+    TcRnStaticFormWarning{}+      -> WarningWithoutFlag     TcRnUselessTypeable       -> WarningWithFlag Opt_WarnDerivingTypeable     TcRnDerivingDefaults{}@@ -3316,6 +3324,8 @@       -> [SuggestRemoveRecordWildcard]     TcRnUnusedName{}       -> noHints+    TcRnStaticFormWarning{}+      -> noHints     TcRnQualifiedBinder{}       -> noHints     TcRnTypeApplicationsDisabled{}@@ -3386,21 +3396,30 @@  pprTcRnBadlyLevelled :: LevelCheckReason -> Set.Set ThLevelIndex -> ThLevelIndex -> Maybe ErrorItem -> DecoratedSDoc pprTcRnBadlyLevelled reason bind_lvls use_lvl lift_attempt = mkDecorated $-         [ fsep [ text "Level error:", pprLevelCheckReason reason-                , text "is bound at" <+> pprThBindLevel bind_lvls-                , text "but used at level" <+> ppr use_lvl]+         [ fsep [ text "Level error:"+                , hang (fsep [what <+> text "is used at level" <+> ppr use_lvl, "but it is bound at" <+> ppr_th_bind_level bind_lvls]) 2+                  if | LevelCheckSplice (unwrapUserRdr -> gre) <- reason+                     , imps <- gre_imp gre+                     , not (isEmptyBag imps) -> ppr_imports imps+                     | otherwise -> empty++                ]          ] ++          [hang (text "Could not be resolved by implicit lifting due to the following error:") 2           (text "No instance for:" <+> quotes (ppr (errorItemPred item)))-         | Just item <- [lift_attempt]-         ] ++-         [ vcat (text "Available from the imports:" : ppr_imports (gre_imp gre))-         | LevelCheckSplice _ (Just gre) <- [reason]-         , not (isEmptyBag (gre_imp gre)) ]+         | Just item <- [lift_attempt] ]   where-    ppr_imports :: Bag ImportSpec -> [SDoc]-    ppr_imports = map ((bullet <+>) . ppr ) . bagToList+    what = case reason of+      LevelCheckInstance _ t -> text "instance for" <+> quotes (ppr t)+      LevelCheckSplice n -> quotes $ ppr $ userRdrName n +    ppr_imports :: Bag ImportSpec -> SDoc+    ppr_imports bag = vcat $ map ((bullet <+>) .  ppr) impspecs+      where impspecs = bagToList bag++ppr_th_bind_level :: Set.Set ThLevelIndex -> SDoc+ppr_th_bind_level levels_set = text "level" <> pluralSet levels_set <+> pprUnquotedSet levels_set+ note :: SDoc -> SDoc note note = "Note" <> colon <+> note <> dot @@ -5820,13 +5839,6 @@     WrongThingTyCon -> "type constructor"     WrongThingAxiom -> "axiom" -pprLevelCheckReason :: LevelCheckReason -> SDoc-pprLevelCheckReason = \case-  LevelCheckInstance _ t ->-    text "instance for" <+> quotes (ppr t)-  LevelCheckSplice t _ ->-    quotes (ppr t)- pprUninferrableTyVarCtx :: UninferrableTyVarCtx -> SDoc pprUninferrableTyVarCtx = \case   UninfTyCtx_ClassContext theta ->@@ -7545,7 +7557,3 @@       text "implements signature" <+> quotes (ppr req_mod_name) <+>       text "in" <+> quotes (ppr req_uid) <> dot -----------------------------------------------------------------------------------pprThBindLevel :: Set.Set ThLevelIndex -> SDoc-pprThBindLevel levels_set = text "level" <> pluralSet levels_set <+> pprUnquotedSet levels_set
GHC/Tc/Errors/Types.hs view
@@ -4441,8 +4441,13 @@     Test cases: T24159_type_syntax_rn_fail   -}   TcRnUnexpectedTypeSyntaxInTerms :: TypeSyntax -> TcRnMessage++  -- `TcRnStaticFormWarning` is a temporary deprecation in GHC 9.14+  TcRnStaticFormWarning :: [Name] -> TcRnMessage+   deriving Generic + ----  data ZonkerMessage where@@ -6242,7 +6247,7 @@  data LevelCheckReason   = LevelCheckInstance !InstanceWhat !PredType-  | LevelCheckSplice !Name !(Maybe GlobalRdrElt)+  | LevelCheckSplice !(WithUserRdr GlobalRdrElt)  data UninferrableTyVarCtx   = UninfTyCtx_ClassContext [TcType]
GHC/Tc/Gen/App.hs view
@@ -3,6 +3,7 @@ {-# LANGUAGE FlexibleContexts    #-} {-# LANGUAGE GADTs               #-} {-# LANGUAGE MultiWayIf          #-}+{-# LANGUAGE RecursiveDo         #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies        #-} {-# LANGUAGE UndecidableInstances #-} -- Wrinkle in Note [Trees That Grow]@@ -47,7 +48,7 @@ import GHC.Core.Type import GHC.Core.Coercion -import GHC.Builtin.Types ( multiplicityTy )+import GHC.Builtin.Types ( multiplicityTy, runtimeRepTy ) import GHC.Builtin.PrimOps( tagToEnumKey ) import GHC.Builtin.Names @@ -59,6 +60,7 @@ import GHC.Types.Var.Env  ( emptyTidyEnv, mkInScopeSet )  import GHC.Data.Maybe+import GHC.Data.FastString  import GHC.Utils.Misc import GHC.Utils.Outputable as Outputable@@ -94,6 +96,8 @@   variables.  We keep track of which variables are instantiation variables   by giving them a TcLevel of QLInstVar, which is like "infinity". +  See Note [QuickLook instantiation variables] in GHC.Tc.Types.TcType.+ (QL2) When we learn what an instantiation variable must be, we simply unify   it with that type; this is done in qlUnify, which is the function mgu_ql(t1,t2)   of the paper.  This may fill in a (mutable) instantiation variable with@@ -102,8 +106,7 @@ (QL3) When QL is done, we turn the instantiation variables into ordinary unification   variables, using qlZonkTcType.  This function fully zonks the type (thereby   revealing all the polytypes), and updates any instantiation variables with-  ordinary unification variables.-  See Note [Instantiation variables are short lived].+  ordinary unification variables. See Note [Instantiation variables are short lived].  (QL4) We cleverly avoid the quadratic cost of QL, alluded to in the paper.   See Note [Quick Look at value arguments]@@ -111,7 +114,7 @@ Note [Instantiation variables are short lived] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * An instantation variable is a mutable meta-type-variable, whose level number-  is QLInstVar.+  is QLInstVar.  See Note [QuickLook instantiation variables] in GHC.Tc.Utils.TcType.  * Ordinary unification variables always stand for monotypes; only instantiation   variables can be unified with a polytype (by `qlUnify`).@@ -264,16 +267,11 @@    In tcInstFun we take a quick look at value arguments, using quickLookArg.    See Note [Quick Look at value arguments]. -   (TCAPP1) Crucially, just before `tcApp` calls `tcInstFun`, it sets the-       ambient TcLevel to QLInstVar, so all unification variables allocated by-       tcInstFun, and in the quick-looks it does at the arguments, will be-       instantiation variables.--   Consider (f (g (h x))).`tcApp` instantiates the call to `f`, and in doing-   so quick-looks at the argument(s), in this case (g (h x)).  But-   `quickLookArg` on (g (h x)) in turn instantiates `g` and quick-looks at-   /its/ argument(s), in this case (h x).  And so on recursively.  Key-   point: all these instantiations make instantiation variables.+   Crucially, `tcInstFun` ensures that all the unification variables+   it allocates, notably by instantiating the function at the head of the+   application, have level QLInstVar, and hence will be "instantiation+   variables", written using \kappa in the paper.+   See Note [Instantiating type variables in QuickLook]  Now we split into two cases: @@ -311,16 +309,6 @@   * Horrible newtype check   * Special case for tagToEnum -(TCAPP2) There is a lurking difficulty in the above plan:-  * Before calling tcInstFun, we set the ambient level in the monad-    to QLInstVar (Step 2 above).-  * Then, when kind-checking the visible type args of the application,-    we may perhaps build an implication constraint.-  * That means we'll try to add 1 to the ambient level; which is a no-op.-  * So skolem escape checks won't work right.-  This is pretty exotic, so I'm just deferring it for now, leaving-  this note to alert you to the possiblity.- Note [Quick Look for particular Ids] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We switch on Quick Look (regardless of -XImpredicativeTypes) for certain@@ -395,9 +383,7 @@        -- Step 3: Instantiate the function type (taking a quick look at args)        ; do_ql <- wantQuickLook rn_fun        ; (inst_args, app_res_rho)-              <- setQLInstLevel do_ql $  -- See (TCAPP1) and (TCAPP2) in-                                         -- Note [tcApp: typechecking applications]-                 tcInstFun do_ql inst_final tc_head fun_sigma rn_args+              <- tcInstFun do_ql inst_final tc_head fun_sigma rn_args         ; case do_ql of             NoQL -> do { traceTc "tcApp:NoQL" (ppr rn_fun $$ ppr app_res_rho)@@ -420,7 +406,7 @@                          -- Step 5.2: typecheck the arguments, and monomorphise                          --           any un-unified instantiation variables                        ; tc_args <- tcValArgs DoQL inst_args-                         -- Step 5.3: zonk to expose the polymophism hidden under+                         -- Step 5.3: zonk to expose the polymorphism hidden under                          --           QuickLook instantiation variables in `app_res_rho`                        ; app_res_rho <- liftZonkM $ zonkTcType app_res_rho @@ -430,10 +416,6 @@                          -- Step 5.5: wrap up                        ; finishApp tc_head tc_args app_res_rho res_wrap } } -setQLInstLevel :: QLFlag -> TcM a -> TcM a-setQLInstLevel DoQL thing_inside = setTcLevel QLInstVar thing_inside-setQLInstLevel NoQL thing_inside = thing_inside- quickLookResultType :: TcRhoType -> ExpRhoType -> TcM () -- This function implements the shaded bit of rule APP-Downarrow in -- Fig 5 of the QL paper: "A quick look at impredicativity" (ICFP'20).@@ -718,11 +700,11 @@       , let no_tvs   = null tvs             no_theta = null theta       , not (no_tvs && no_theta)-      = do { (_inst_tvs, wrap, fun_rho) <-+      = do { (wrap, fun_rho) <-                 -- addHeadCtxt: important for the class constraints                 -- that may be emitted from instantiating fun_sigma                 addHeadCtxt fun_ctxt $-                instantiateSigma fun_orig fun_conc_tvs tvs theta body2+                instantiateSigmaQL do_ql fun_orig fun_conc_tvs tvs theta body2                   -- See Note [Representation-polymorphism checking built-ins]                   -- in GHC.Tc.Utils.Concrete.                   -- NB: we are doing this even when "acc" is not empty,@@ -785,7 +767,7 @@         --     not defer in any way, because this is a QL instantiation variable.         -- It's easier just to do the job directly here.         do { arg_tys <- zipWithM new_arg_ty (leadingValArgs args) [pos..]-           ; res_ty  <- newOpenFlexiTyVarTy+           ; res_ty  <- newOpenFlexiTyVarTyQL do_ql TauTv            ; let fun_ty' = mkScaledFunTys arg_tys res_ty             -- Fill in kappa := nu_1 -> .. -> nu_n -> res_nu@@ -825,12 +807,12 @@     new_arg_ty :: LHsExpr GhcRn -> Int -> TcM (Scaled TcType)     -- Make a fresh nus for each argument in rule IVAR     new_arg_ty (L _ arg) i-      = do { arg_nu <- newOpenFlexiFRRTyVarTy $+      = do { arg_nu <- newArgTyVarTyQL do_ql $                        FRRExpectedFunTy (ExpectedFunTyArg (HsExprTcThing tc_fun) arg) i                -- Following matchActualFunTy, we create nu_i :: TYPE kappa_i[conc],                -- thereby ensuring that the arguments have concrete runtime representations -           ; mult_ty <- newFlexiTyVarTy multiplicityTy+            ; mult_ty <- newFlexiTyVarTyQL do_ql (mkTyVarOccFS (fsLit "m")) TauTv multiplicityTy                -- mult_ty: e need variables for argument multiplicities (#18731)                -- Otherwise, 'undefined x' wouldn't be linear in x @@ -913,6 +895,138 @@  {- ********************************************************************* *                                                                      *+              Instantiating fresh type variables++      Functions in here use getTcLevelQL to decide what level+      to put on fresh unification variables.  If do_ql = DoQL, we+      ignore the level in the monad, and use QLInstVar instead,+      thereby giving birth to a Quick Look instantiation varaible+*                                                                      *+********************************************************************* -}++{- Note [Instantiating type variables in QuickLook]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+During QuickLook, when we instantiate a function's type (specifically, in+`tcInstFun`), we must instantiate it with so-called "instantiation variables".+See Note [QuickLook instantiation variables] in GHC.Tc.Utils.TcType.++So `tcInstFun` uses a family of specialised functions, defined below, like+   instantiateSigmaQL+   newFlexiTyVarTyQL+   etc+that create fresh instantiation variables rather than regular unification+variables.   But only if QuickLook is on!  So they all take a `QLFlag` to+tell them what to do; that flag is ultimately used in `getTcLevelQL`.++There is some code duplication between these functions and their friends+in GHC.Tc.Utils.TcMType, but that's just too bad.++Note that `tcInstFun` calls `quickLookArg` which calls `tcInstFun` recursively.+Consider (f (g (h x))).`tcApp` instantiates the call to `f`, and in doing so+quick-looks at the argument(s), in this case (g (h x)).  But `quickLookArg` on (g+(h x)) in turn instantiates `g` and quick-looks at /its/ argument(s), in this+case (h x).  And so on recursively.  Key point: all these instantiations make+instantiation variables.+-}++getTcLevelQL :: QLFlag -> TcM TcLevel+-- If Quick Look is on, instantiate all fresh unification variables+-- at level QLInstVar; they are instantiation variables+-- See Note [Instantiating type variables in QuickLook]+getTcLevelQL DoQL = return QLInstVar+getTcLevelQL NoQL = getTcLevel++newFlexiTyVarQL :: QLFlag -> OccName -> MetaInfo -> TcKind -> TcM TcTyVar+newFlexiTyVarQL do_ql occ info kind+  = do { lvl  <- getTcLevelQL do_ql+       ; ref  <- newMutVar Flexi+       ; name <- newSysName occ -- See Note [Name of a unification variable]+                                -- in GHC.Tc.Utils.TcMType+       ; let details = MetaTv { mtv_info  = info+                              , mtv_ref   = ref+                              , mtv_tclvl = lvl }+       ; return (mkTcTyVar name kind details) }++newFlexiTyVarTyQL :: QLFlag -> OccName -> MetaInfo -> TcKind -> TcM TcType+newFlexiTyVarTyQL do_ql occ info kind+  = mkTyVarTy <$> newFlexiTyVarQL do_ql occ info kind++newOpenFlexiTyVarTyQL :: QLFlag -> MetaInfo -> TcM TcType+newOpenFlexiTyVarTyQL do_ql rr_info+  = do { let rr_occ = mkTyVarOccFS (fsLit "cx")+             tv_occ = mkTyVarOccFS (fsLit "q")+        ; rr_ty  <- newFlexiTyVarTyQL do_ql rr_occ rr_info runtimeRepTy+        ; arg_nu <- newFlexiTyVarTyQL do_ql tv_occ TauTv   (mkTYPEapp rr_ty)+        ; return arg_nu }++newArgTyVarTyQL :: QLFlag -> FixedRuntimeRepContext -> TcM TcType+newArgTyVarTyQL do_ql frr_ctxt+  = mdo { let conc_orig = ConcreteFRR $+                          FixedRuntimeRepOrigin+                            { frr_context = frr_ctxt+                            , frr_type    = arg_nu }+        ; rr_info <- mkConcreteInfo conc_orig+        ; arg_nu  <- newOpenFlexiTyVarTyQL do_ql rr_info+        ; return arg_nu }++instantiateSigmaQL :: QLFlag+                   -> CtOrigin+                   -> ConcreteTyVars -- ^ concreteness information+                   -> [TyVar]+                   -> TcThetaType -> TcSigmaType+                   -> TcM (HsWrapper, TcSigmaType)+-- (instantiateSigmaQL orig tvs theta ty)+--     instantiates the type variables tvs, emits the (instantiated)+--     constraints theta, and returns the (instantiated) type ty+-- See Note [Instantiating type variables in QuickLook]+instantiateSigmaQL do_ql orig concs tvs theta body_ty+  = do { rec (subst, inst_tvs) <- mapAccumLM (new_meta subst) empty_subst tvs+       ; let inst_theta  = substTheta subst theta+             inst_body   = substTy subst body_ty++       ; wrap <- instCall orig (mkTyVarTys inst_tvs) inst_theta+       ; traceTc "Instantiating"+                 (vcat [ text "origin" <+> pprCtOrigin orig+                       , text "tvs"   <+> ppr tvs+                       , text "theta" <+> ppr theta+                       , text "type" <+> debugPprType body_ty+                       , text "with" <+> ppr inst_tvs+                       , text "theta:" <+> ppr inst_theta ])++      ; return (wrap, inst_body) }+  where+    in_scope = mkInScopeSet (tyCoVarsOfType (mkSpecSigmaTy tvs theta body_ty))+               -- mkSpecSigmaTy: Inferred vs Specified is not important here;+               --                We just want an accurate free-var set+    empty_subst = mkEmptySubst in_scope++    new_meta :: Subst -> Subst -> TyVar -> TcM (Subst, TcTyVar)+    new_meta final_subst subst tv+      = do { let occ = getOccName tv+                 substd_kind = substTy subst (tyVarKind tv)+           ; info   <- get_info final_subst tv+           ; new_tv <- newFlexiTyVarQL do_ql occ info substd_kind+           ; let new_subst   = extendTvSubstWithClone subst tv new_tv+           ; return (new_subst, new_tv) }++    get_info :: Subst -> TyVar -> TcM MetaInfo+    get_info final_subst tv+      -- Is this a type variable that must be instantiated to a concrete type?+      -- If so, create a ConcreteTv metavariable instead of a plain TauTv.+      -- See Note [Representation-polymorphism checking built-ins]+      --     in GHC.Tc.Utils.Concrete.++      | Just conc_orig0 <- lookupNameEnv concs (tyVarName tv)+      , let conc_orig = substConcreteTvOrigin final_subst body_ty conc_orig0+                        -- See Note [substConcreteTvOrigin].+      = mkConcreteInfo conc_orig++      -- The vastly common case+      | otherwise+      = return TauTv++{- *********************************************************************+*                                                                      *               Visible type application *                                                                      * ********************************************************************* -}@@ -2096,11 +2210,9 @@   discard the constraints and the coercion, and do not update the instantiation   variable.  But see "Sadly discarded design alternative" below.) -  See also (TCAPP2) in Note [tcApp: typechecking applications].- (UQL3) Instantiation variables don't really have a settled level yet;-  they have level QLInstVar (see Note [The QLInstVar TcLevel] in GHC.Tc.Utils.TcType.-  You might worry that we might unify+  they have level QLInstVar (see Note [QuickLook instantiation variables]+  in GHC.Tc.Utils.TcType.  You might worry that we might unify       alpha[1] := Maybe kappa[qlinst]   and later this kappa turns out to be a level-2 variable, and we have committed   a skolem-escape error.
GHC/Tc/Gen/Export.hs view
@@ -453,7 +453,7 @@                let avail = availFromGRE gre                    name = greName gre -               checkThLocalNameNoLift (ieLWrappedUserRdrName l name)+               checkThLocalNameNoLift $ ieLWrappedUserRdrName l gre                occs' <- check_occs occs ie [gre]                (export_warn_spans', dont_warn_export', warn_txt_rn)                  <- process_warning export_warn_spans@@ -502,7 +502,7 @@                     occs' <- check_occs occs ie [gre]                     return (Just avail, occs', exp_dflts) -               checkThLocalNameNoLift (ieLWrappedUserRdrName l name)+               checkThLocalNameNoLift (ieLWrappedUserRdrName l gre)                (export_warn_spans', dont_warn_export', warn_txt_rn)                  <- process_warning export_warn_spans                                     dont_warn_export@@ -530,7 +530,7 @@                    all_gres = par : all_kids                    all_names = map greName all_gres -               checkThLocalNameNoLift (ieLWrappedUserRdrName l name)+               checkThLocalNameNoLift (ieLWrappedUserRdrName l par)                occs' <- check_occs occs ie all_gres                (export_warn_spans', dont_warn_export', warn_txt_rn)                  <- process_warning export_warn_spans@@ -568,7 +568,7 @@                    all_gres = par : all_kids                    all_names = map greName all_gres -               checkThLocalNameNoLift (ieLWrappedUserRdrName l name)+               checkThLocalNameNoLift (ieLWrappedUserRdrName l par)                occs' <- check_occs occs ie all_gres                (export_warn_spans', dont_warn_export', warn_txt_rn)                  <- process_warning export_warn_spans@@ -705,8 +705,8 @@       = addUsedGREs ExportDeprecationWarnings (pickGREs parent_rdr kid_gres)  -ieLWrappedUserRdrName :: LIEWrappedName GhcPs -> Name -> LIdOccP GhcRn-ieLWrappedUserRdrName l n = fmap (\rdr -> WithUserRdr rdr n) $ ieLWrappedName l+ieLWrappedUserRdrName :: LIEWrappedName GhcPs -> n -> GenLocated SrcSpanAnnN (WithUserRdr n)+ieLWrappedUserRdrName l n = (\rdr -> WithUserRdr rdr n) <$> ieLWrappedName l  -- | In what namespaces should we go looking for an import/export item -- that is out of scope, for suggestions in error messages?@@ -812,7 +812,7 @@                  ; return (L l (IEName noExtField (L (l2l l) ub)), gre)}             FoundChild child@(GRE { gre_name = child_nm, gre_par = par }) ->               do { checkPatSynParent spec_parent par child_nm-                 ; checkThLocalNameNoLift (ieLWrappedUserRdrName n child_nm)+                 ; checkThLocalNameNoLift (ieLWrappedUserRdrName n child)                  ; return (replaceLWrappedName n child_nm, child)                  }             IncorrectParent p c gs -> failWithDcErr (parentGRE_name p) (greName c) gs
GHC/Tc/Gen/Expr.hs view
@@ -573,9 +573,12 @@               tcCheckPolyExprNC expr expr_ty          -- Check that the free variables of the static form are closed.-        -- It's OK to use nonDetEltsUniqSet here as the only side effects of-        -- checkClosedInStaticForm are error messages.-        ; mapM_ checkClosedInStaticForm $ nonDetEltsUniqSet fvs+        -- Complain about nested-bound free vars+        -- This is a deprecation warning in 9.14 only+        -- In 10.0 it becomes an error+        ; bad_fvs <- filterM checkClosedInStaticForm (nameSetElemsStable fvs)+        ; unless (null bad_fvs) $+          addDiagnostic (TcRnStaticFormWarning bad_fvs)          -- Require the type of the argument to be Typeable.         ; typeableClass <- tcLookupClass typeableClassName@@ -1798,15 +1801,24 @@ -}  -- | Checks if the given name is closed and emits an error if not.+-- Returns True if the name is a nested let-bound variable, for the+-- deprecation warning. -- -- See Note [Not-closed error messages].-checkClosedInStaticForm :: Name -> TcM ()+checkClosedInStaticForm :: Name -> TcM Bool checkClosedInStaticForm name = do     type_env <- getLclTypeEnv     case checkClosed type_env name of-      Nothing -> return ()-      Just reason -> addErrTc $ explain name reason+      Nothing -> return (nested_term_var type_env)+      Just reason -> do addErrTc $ explain name reason+                        return False   where+    nested_term_var :: TcTypeEnv -> Bool+    nested_term_var type_env+      | isExternalName name = False+      | Just (ATcId {}) <- lookupNameEnv type_env name = True+      | otherwise = False+     -- See Note [Checking closedness].     checkClosed :: TcTypeEnv -> Name -> Maybe NotClosedReason     checkClosed type_env n = checkLoop type_env (unitNameSet n) n
GHC/Tc/Gen/HsType.hs view
@@ -1268,8 +1268,10 @@   = checkExpKind rn_ty liftedTypeKind liftedTypeKind exp_kind  --------- Literals-tcHsType _ rn_ty@(HsTyLit _ (HsNumTy _ n)) exp_kind-  = do { checkWiredInTyCon naturalTyCon+tcHsType _ rn_ty@(HsTyLit _ (HsNumTy x n)) exp_kind+  = do { when (n < 0) $+           addErr $ TcRnNegativeNumTypeLiteral (HsNumTy x n)+       ; checkWiredInTyCon naturalTyCon        ; checkExpKind rn_ty (mkNumLitTy n) naturalTy exp_kind }  tcHsType _ rn_ty@(HsTyLit _ (HsStrTy _ s)) exp_kind
GHC/Tc/Gen/Pat.hs view
@@ -21,6 +21,7 @@    , tcCheckPat, tcCheckPat_O, tcInferPat    , tcMatchPats    , addDataConStupidTheta+   , zipPatsBndrs    ) where @@ -1721,7 +1722,7 @@                          , [(HsTyPat GhcRn, TyVar)]   -- Existentials                          , HsConPatDetails GhcRn )    -- Value arguments split_con_ty_args fixity con_like arg_pats = do-  (bndr_ty_arg_prs, value_args) <- zip_pats_bndrs arg_pats (conLikeUserTyVarBinders con_like)+  (bndr_ty_arg_prs, value_args) <- zipPatsBndrs arg_pats (conLikeUserTyVarBinders con_like)   return $ if null ex_tvs  -- Short cut common case            then (bndr_ty_arg_prs, [], mk_details fixity value_args)            else let (ex_prs, univ_prs) = partition is_existential bndr_ty_arg_prs@@ -1737,24 +1738,75 @@       -- InfixCon becomes PrefixCon if there are fewer than 2 value arguments.       -- Test case: T25127_infix -zip_pats_bndrs :: [LPat GhcRn] -> [TyVarBinder] -> TcM ([(HsTyPat GhcRn, TyVar)], [LPat GhcRn])-zip_pats_bndrs (L loc pat : pats) (Bndr tv vis : tvbs)+-- | Line the arguments of a 'ConPat' up against the 'TyVarBinder's of its+-- 'ConLike', returning the type arguments with the binders they instantiate,+-- and the remaining value arguments.+--+-- See Note [Zipping ConPat arguments with TyVarBinders]+--+-- Precondition: 'check_con_pat_arity' has passed for these arguments, so that+-- we never run out of patterns while a required binder remains.+zipPatsBndrs :: [LPat GhcRn] -> [TyVarBinder] -> TcM ([(HsTyPat GhcRn, TyVar)], [LPat GhcRn])+zipPatsBndrs (L loc pat : pats) (Bndr tv vis : tvbs)   | isVisibleForAllTyFlag vis   = do { tp <- setSrcSpanA loc $ pat_to_type_pat pat-       ; (prs, pats') <- zip_pats_bndrs pats tvbs+       ; (prs, pats') <- zipPatsBndrs pats tvbs        ; return ((tp, tv) : prs, pats') }   | InvisPat pat_spec tp <- pat   , Invisible spec <- vis   , pat_spec == spec-  = do { (prs, pats') <- zip_pats_bndrs pats tvbs+  = do { (prs, pats') <- zipPatsBndrs pats tvbs        ; return ((tp, tv):prs, pats') }-zip_pats_bndrs pats (Bndr _ vis : tvbs)-  -- zip_pats_bndrs [] (Bndr _ Required : tvbs)+zipPatsBndrs pats (Bndr _ vis : tvbs)+  -- zipPatsBndrs [] (Bndr _ Required : tvbs)   --   is ruled out by the arity check in splitConTyArgs,   --   so we can assume (isInvisibleForAllTyFlag vis)   = do { massert (isInvisibleForAllTyFlag vis)-       ; zip_pats_bndrs pats tvbs }-zip_pats_bndrs pats [] = return ([], pats)+       ; zipPatsBndrs pats tvbs }+zipPatsBndrs pats [] = return ([], pats)++{- Note [Zipping ConPat arguments with TyVarBinders]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+The zipPatsBndrs function allows us to line up the arguments of a constructor+pattern `MkT p1 p2 ... pn` with the TyVarBinders of MkT's type. Consider++  MkT :: forall a b. forall c d -> a -> T a b c d++Then, in a pattern match `MkT @s (type t) p q`, we have the following+correspondence:++  * pattern `@s`     with the TyVarBinder `forall a.`+  * no pattern       with the TyVarBinder `forall b.`+  * pattern `type t` with the TyVarBinder `forall c ->`+  * pattern `p`      with the TyVarBinder `forall d ->`+  * pattern `q`      is the one remaining value argument++Note how `p` and `q` are exactly alike, and only the TyVarBinder can tell us+that `p` is a required type argument rather than a value argument.++So the call (zipPatsBndrs pats tvbs) with the inputs++  pats  =   [@s, type t, p, q]+  tvbs  =   [Bndr a Spec, Bndr b Spec, Bndr c Req, Bndr d Req]++produces the following (ty_pats, val_pats) outputs:++  ty_pats  = [(s, a), (t, c), (p, d)]+  val_pats = [q]   -- remaining value arguments++Note that the ty_pats components are stripped: the type patterns have lost the+`@` or the `type` herald, and the binders have been reduced to their TyVars.++This is currently used in two ways:++1. In tcDataConPat/tcPatSynPat (via splitConTyArgs) to pass the type arguments+   onto tcConTyArgs and the value arguments onto tcConValArgs.+   See Note [Type applications in patterns] for more details.++2. In tcPatToExpr, to discard the type arguments in the RHS of an implicitly+   bidirectional pattern synonym, keeping only the value arguments.+   See Note [Discarding types in the builder expression] in GHC.Tc.TyCl.PatSyn.+-}  tcConTyArgs :: Subst -> PatEnv -> [(HsTyPat GhcRn, TyVar)]             -> TcM a -> TcM a
GHC/Tc/Instance/Class.hs view
@@ -20,7 +20,7 @@ import GHC.Tc.Utils.TcMType import GHC.Tc.Types.Evidence import GHC.Tc.Types.CtLoc-import GHC.Tc.Types.Origin ( InstanceWhat (..), SafeOverlapping, CtOrigin(GetFieldOrigin) )+import GHC.Tc.Types.Origin ( InstanceWhat (..), SafeOverlapping, isHasFieldOrigin ) import GHC.Tc.Instance.Family( tcGetFamInstEnvs, tcLookupDataFamInst, FamInstEnvs )  import GHC.Rename.Env( addUsedGRE, addUsedDataCons, DeprecationWarnings (..) )@@ -49,6 +49,7 @@ import GHC.Core.DataCon import GHC.Core.TyCon import GHC.Core.Class+import GHC.Core.Utils( mkCast ) import GHC.Core ( Expr(..), mkConApp )  import GHC.StgToCmm.Closure ( isSmallFamily )@@ -455,7 +456,7 @@                = mkCoreLams [ runtimeRep1TyVar, openAlphaTyVar, sv, k ] $                  Var k `App` (evUnaryDictAppE cls dict_args meth_arg)                where-                 meth_arg = Var sv `Cast` mkSubCo (evExprCoercion ev_expr)+                 meth_arg = Var sv `mkCast` mkSubCo (evExprCoercion ev_expr)         ; let mk_ev [c] = evDictApp wd_cls [cls_ty, mty] [evWithDict c]              mk_ev e   = pprPanic "matchWithDict" (ppr e)@@ -657,7 +658,7 @@                                (mkReflCo Representational intPrimTy)      -> do { addUsedDataCons rdr_env repTyCon   -- See wrinkles DTW2 and DTW3            ; let mk_ev _ = evDictApp dataToTagClass [levity, dty] $-                           [methodRep `Cast` methodCo]+                           [methodRep `mkCast` methodCo]            ; pure (OneInst { cir_new_theta = [] -- (Ignore stupid theta.)                            , cir_mk_ev     = mk_ev                            , cir_canonical = EvCanonical@@ -1274,8 +1275,8 @@ -- Warn about incomplete record selectors -- See (IRS6) in Note [Detecting incomplete record selectors] in GHC.HsToCore.Pmc warnIncompleteRecSel dflags sel_id ct_loc-  | not (isGetFieldOrigin (ctLocOrigin ct_loc))-      -- isGetFieldOrigin: see (IRS7) in+  | not $ isHasFieldOrigin (ctLocOrigin ct_loc)+      -- isHasFieldOrigin: see (IRS7) in       -- Note [Detecting incomplete record selectors] in GHC.HsToCore.Pmc   , RecSelId { sel_cons = RSI { rsi_undef = fallible_cons } } <- idDetails sel_id   , not (null fallible_cons)@@ -1286,11 +1287,6 @@   = return ()   where     maxCons = maxUncoveredPatterns dflags--    -- GHC.Tc.Gen.App.tcInstFun arranges that the CtOrigin of (r.x) is GetFieldOrigin,-    -- despite the expansion to (getField @"x" r)-    isGetFieldOrigin (GetFieldOrigin {}) = True-    isGetFieldOrigin _                   = False  lookupHasFieldLabel   :: FamInstEnvs -> GlobalRdrEnv -> [Type]
GHC/Tc/Solver/Dict.hs view
@@ -264,7 +264,9 @@ * In `updInertDicts`, in this module, when adding [G] (?x :: ty), remove any   existing [G] (?x :: ty'), regardless of ty'. -* Wrinkle (SIP1): we must be careful of superclasses.  Consider+There are wrinkles:++* Wrinkle (SIP1): we must be careful of superclasses (#14218).  Consider      f,g :: (?x::Int, C a) => a -> a      f v = let ?x = 4 in g v @@ -272,24 +274,31 @@   We must /not/ solve this from the Given (?x::Int, C a), because of   the intervening binding for (?x::Int).  #14218. -  We deal with this by arranging that when we add [G] (?x::ty) we delete+  We deal with this by arranging that when we add [G] (?x::ty) we /delete/   * from the inert_cans, and   * from the inert_solved_dicts   any existing [G] (?x::ty) /and/ any [G] D tys, where (D tys) has a superclass   with (?x::ty).  See Note [Local implicit parameters] in GHC.Core.Predicate. -  An important special case is constraint tuples like [G] (% ?x::ty, Eq a %).-  But it could happen for `class xx => D xx where ...` and the constraint D-  (?x :: int).  This corner (constraint-kinded variables instantiated with-  implicit parameter constraints) is not well explored.+  An very important special case is constraint tuples like [G] (% ?x::ty, Eq a %). -  Example in #14218, and #23761+  But it could also happen for `class xx => D xx where ...` and the constraint+  D (?x :: int); again see Note [Local implicit parameters].  This corner+  (constraint-kinded variables instantiated with implicit parameter constraints)+  is not well explored. +  You might worry about whether deleting an /entire/ constraint just because+  a distant superclass has an implicit parameter might make another Wanted for+  that constraint un-solvable.  Indeed so. But for constraint tuples it doesn't+  matter -- their entire payload is their superclasses.  And the other case is+  the ill-explored corner above.+   The code that accounts for (SIP1) is in updInertDicts; in particular the call to   GHC.Core.Predicate.mentionsIP.  * Wrinkle (SIP2): we must apply this update semantics for `inert_solved_dicts`-  as well as `inert_cans`.+  as well as `inert_cans` (#23761).+   You might think that wouldn't be necessary, because an element of   `inert_solved_dicts` is never an implicit parameter (see   Note [Solved dictionaries] in GHC.Tc.Solver.InertSet).@@ -301,6 +310,19 @@    Now (C (?x::Int)) has a superclass (?x::Int). This may look exotic, but it   happens particularly for constraint tuples, like `(% ?x::Int, Eq a %)`.++* Wrinkle (SIP3)+  - Note that for the inert dictionaries, `inert_cans`, we must /only/ delete+    existing /Givens/!  Deleting an existing Wanted led to #26451; we just never+    solved it!++  - In contrast, the solved dictionaries, `inert_solved_dicts`, are really like+    Givens; they may be "inherited" from outer scopes, so we must delete any+    solved dictionaries for this implicit parameter for /both/ Givens /and/+    Wanteds.++    Otherwise the new Given doesn't properly shadow those inherited solved+    dictionaries. Test T23761 showed this up.  Example 1: 
GHC/Tc/Solver/Monad.hs view
@@ -385,28 +385,53 @@ -}  updInertDicts :: DictCt -> TcS ()-updInertDicts dict_ct@(DictCt { di_cls = cls, di_ev = ev, di_tys = tys })-  = do { traceTcS "Adding inert dict" (ppr dict_ct $$ ppr cls  <+> ppr tys)+updInertDicts dict_ct+  = do { traceTcS "Adding inert dict" (ppr dict_ct) -       ; if | isGiven ev, Just (str_ty, _) <- isIPPred_maybe cls tys-            -> -- For [G] ?x::ty, remove any dicts mentioning ?x,-              --    from /both/ inert_cans /and/ inert_solved_dicts (#23761)-               -- See (SIP1) and (SIP2) in Note [Shadowing of implicit parameters]-               updInertSet $ \ inerts@(IS { inert_cans = ics, inert_solved_dicts = solved }) ->-               inerts { inert_cans         = updDicts (filterDicts (does_not_mention_ip_for str_ty)) ics-                      , inert_solved_dicts = filterDicts (does_not_mention_ip_for str_ty) solved }-            | otherwise-            -> return ()+       -- For Given implicit parameters (only), delete any existing+       -- Givens for the same implicit parameter.+       -- See Note [Shadowing of implicit parameters]+       ; deleteGivenIPs dict_ct+        -- Add the new constraint to the inert set        ; updInertCans (updDicts (addDict dict_ct)) }++deleteGivenIPs :: DictCt -> TcS ()+-- Special magic when adding a Given implicit parameter to the inert set+-- For [G] ?x::ty, remove any existing /Givens/ mentioning ?x,+--    from /both/ inert_cans /and/ inert_solved_dicts (#23761)+-- See Note [Shadowing of implicit parameters]+deleteGivenIPs (DictCt { di_cls = cls, di_ev = ev, di_tys = tys })+  | isGiven ev+  , Just (str_ty, _) <- isIPPred_maybe cls tys+  = updInertSet $ \ inerts@(IS { inert_cans = ics, inert_solved_dicts = solved }) ->+    inerts { inert_cans         = updDicts (filterDicts (keep_can str_ty)) ics+           , inert_solved_dicts = filterDicts (keep_solved str_ty) solved }+  | otherwise+  = return ()   where-    -- Does this class constraint or any of its superclasses mention-    -- an implicit parameter (?str :: ty) for the given 'str' and any type 'ty'?-    does_not_mention_ip_for :: Type -> DictCt -> Bool-    does_not_mention_ip_for str_ty (DictCt { di_cls = cls, di_tys = tys })-      = not $ mightMentionIP (not . typesAreApart str_ty) (const True) cls tys-        -- See Note [Using typesAreApart when calling mightMentionIP]-        -- in GHC.Core.Predicate+    keep_can, keep_solved :: Type -> DictCt -> Bool+    -- keep_can: we keep an inert dictionary UNLESS+    --   (1) it is a Given+    --   (2) it binds an implicit parameter (?str :: ty) for the given 'str'+    --       regardless of 'ty', possibly via its superclasses+    -- The test is a bit conservative, hence `mightMentionIP` and `typesAreApart`+    -- See Note [Using typesAreApart when calling mightMentionIP]+    -- in GHC.Core.Predicate+    --+    -- keep_solved: same as keep_can, but for /all/ constraints not just Givens+    --+    -- Why two functions?  See (SIP3) in Note [Shadowing of implicit parameters]+    keep_can str (DictCt { di_ev = ev, di_cls = cls, di_tys = tys })+      = not (isGiven ev                -- (1)+          && mentions_ip str cls tys)  -- (2)+    keep_solved str (DictCt { di_cls = cls, di_tys = tys })+      = not (mentions_ip str cls tys)++    -- mentions_ip: the inert constraint might provide evidence+    -- for an implicit parameter (?str :: ty) for the given 'str'+    mentions_ip str cls tys+      = mightMentionIP (not . typesAreApart str) (const True) cls tys  updInertIrreds :: IrredCt -> TcS () updInertIrreds irred
GHC/Tc/TyCl/PatSyn.hs view
@@ -138,7 +138,7 @@        ; (tclvl, wanted, ((lpat', args), pat_ty))             <- pushLevelAndCaptureConstraints      $                tcInferPat FRRPatSynArg PatSyn lpat $-               mapM tcLookupId arg_names+               mapM tcLookupPatSynArg arg_names         ; let (ex_tvs, prov_dicts) = tcCollectEx lpat' @@ -473,7 +473,7 @@            -- location to x's binding site in lpat, namely the 'x' in Just (x,True).            -- Else the error message location is wherever tcCheckPat finished,            -- namely the right-hand corner of the pattern-        do { arg_id <- tcLookupId arg_name+        do { arg_id <- tcLookupPatSynArg arg_name            ; wrap <- tcSubTypeSigma (OccurrenceOf (idName arg_id))                                     GenSigCtxt                                     (idType arg_id)@@ -646,6 +646,19 @@     InfixCon name1 name2 -> (map unLoc [name1, name2], True)     RecCon names         -> (map (unLoc . recordPatSynPatVar) names, False) +-- | Look up the 'Id' bound by the pattern for a declared argument of a pattern+-- synonym. With @RequiredTypeArguments@ the argument may turn out to be a type+-- variable, e.g. @pattern P x = MkT x@ where the argument of @MkT@ is a required+-- type argument; then we report an illegal term-level use of @x@ (#27586).+tcLookupPatSynArg :: Name -> TcM Id+tcLookupPatSynArg arg_name+  = do { thing <- tcLookup arg_name+       ; case thing of+           ATcId { tct_id = id } -> return id+           AGlobal (AnId id)     -> return id+           ATyVar {}             -> failIllegalTyVar (noUserRdr arg_name)+           _                     -> pprPanic "tcLookupPatSynArg" (ppr arg_name) }+ wrongNumberOfParmsErr :: Name -> Arity -> Arity -> TcM a wrongNumberOfParmsErr name decl_arity missing   = failWithTc $ TcRnPatSynArityMismatch name decl_arity missing@@ -893,11 +906,9 @@   | isUnidirectional dir   = return [] -  | Left why <- mb_match_group       -- Can't invert the pattern-  = setSrcSpan (getLocA lpat) $ failWithTc $ TcRnPatSynInvalidRhs ps_name lpat args why--  | Right match_group <- mb_match_group  -- Bidirectional-  = do { patsyn <- tcLookupPatSyn ps_name+  | otherwise                        -- Bidirectional+  = do { match_group <- get_match_group+       ; patsyn <- tcLookupPatSyn ps_name        ; case patSynBuilder patsyn of {            Nothing -> return [] ;              -- This case happens if we found a type error in the@@ -938,10 +949,10 @@        ; return builder_binds } } }    where-    mb_match_group+    get_match_group        = case dir of-           ExplicitBidirectional explicit_mg -> Right explicit_mg-           ImplicitBidirectional -> fmap mk_mg (tcPatToExpr args lpat)+           ExplicitBidirectional explicit_mg -> return explicit_mg+           ImplicitBidirectional -> mk_mg <$> tcPatToExpr ps_name args lpat            Unidirectional -> panic "tcPatSynBuilderBind"      mk_mg :: LHsExpr GhcRn -> MatchGroup GhcRn (LHsExpr GhcRn)@@ -985,44 +996,53 @@   | need_dummy_arg = mkVisFunTyMany unboxedUnitTy ty   | otherwise      = ty -tcPatToExpr :: [LocatedN Name] -> LPat GhcRn-            -> Either PatSynInvalidRhsReason (LHsExpr GhcRn)+tcPatToExpr :: Name -> [LocatedN Name] -> LPat GhcRn -> TcM (LHsExpr GhcRn) -- Given a /pattern/, return an /expression/ that builds a value -- that matches the pattern.  E.g. if the pattern is (Just [x]), -- the expression is (Just [x]).  They look the same, but the -- input uses constructors from HsPat and the output uses constructors -- from HsExpr. ----- Returns (Left r) if the pattern is not invertible, for reason r.+-- Fails with TcRnPatSynInvalidRhs if the pattern is not invertible. -- See Note [Builder for a bidirectional pattern synonym]-tcPatToExpr args pat = go pat+tcPatToExpr ps_name args pat = go pat   where     lhsVars = mkNameSet (map unLoc args) +    invalidRhs :: PatSynInvalidRhsReason -> TcM a+    invalidRhs why = setSrcSpan (getLocA pat) $+                     failWithTc $ TcRnPatSynInvalidRhs ps_name pat args why+     -- Make a prefix con for prefix and infix patterns for simplicity     mkPrefixConExpr :: LocatedN (WithUserRdr Name)                     -> [LPat GhcRn]-                    -> Either PatSynInvalidRhsReason (HsExpr GhcRn)-    mkPrefixConExpr lcon@(L loc _) pats-      = do { exprs <- mapM go pats+                    -> TcM (HsExpr GhcRn)+    mkPrefixConExpr lcon@(L loc con_name) pats+      = do { con_like <- tcLookupConLike con_name+           ; let tvbs = conLikeUserTyVarBinders con_like+           ; (_ty_pats, val_pats) <- zipPatsBndrs pats tvbs+                -- Type arguments _ty_pats are discarded, just like the SigPat's type.+                -- See Note [Discarding types in the builder expression]+           ; let ty_exprs = [wildCardTyArg | tvb <- tvbs, isVisibleForAllTyBinder tvb]+                -- Placeholders `_` for the discarded required type arguments.+           ; val_exprs <- mapM go val_pats            ; let con = L (l2l loc) (HsVar noExtField lcon)-           ; return (unLoc $ mkHsApps con exprs)-           }+           ; return (unLoc $ mkHsApps con (ty_exprs ++ val_exprs)) }      mkRecordConExpr :: LocatedN (WithUserRdr Name)                     -> HsRecFields GhcRn (LPat GhcRn)-                    -> Either PatSynInvalidRhsReason (HsExpr GhcRn)+                    -> TcM (HsExpr GhcRn)     mkRecordConExpr con (HsRecFields x fields dd)       = do { exprFields <- mapM go' fields            ; return (RecordCon noExtField con (HsRecFields x exprFields dd)) } -    go' :: LHsRecField GhcRn (LPat GhcRn) -> Either PatSynInvalidRhsReason (LHsRecField GhcRn (LHsExpr GhcRn))+    go' :: LHsRecField GhcRn (LPat GhcRn) -> TcM (LHsRecField GhcRn (LHsExpr GhcRn))     go' (L l rf) = L l <$> traverse go rf -    go :: LPat GhcRn -> Either PatSynInvalidRhsReason (LHsExpr GhcRn)+    go :: LPat GhcRn -> TcM (LHsExpr GhcRn)     go (L loc p) = L loc <$> go1 p -    go1 :: Pat GhcRn -> Either PatSynInvalidRhsReason (HsExpr GhcRn)+    go1 :: Pat GhcRn -> TcM (HsExpr GhcRn)     go1 (ConPat NoExtField con info)       = case info of           PrefixCon ps   -> mkPrefixConExpr con ps@@ -1030,13 +1050,13 @@           RecCon fields  -> mkRecordConExpr con fields      go1 (SigPat _ pat _) = go1 (unLoc pat)-        -- See Note [Type signatures and the builder expression]+        -- See Note [Discarding types in the builder expression]      go1 (VarPat _ (L l var))         | var `elemNameSet` lhsVars         = return $ mkHsVar (L l var)         | otherwise-        = Left (PatSynUnboundVar var)+        = invalidRhs (PatSynUnboundVar var)     go1 (ParPat _ pat) = fmap (HsPar noExtField) (go pat)     go1 (ListPat _ pats)       = do { exprs <- mapM go pats@@ -1056,10 +1076,7 @@         | otherwise                 = return $ HsOverLit noExtField n     go1 (SplicePat (HsUntypedSpliceTop _ pat) _) = go1 pat     go1 (SplicePat (HsUntypedSpliceNested _) _)  = panic "tcPatToExpr: invalid nested splice"-    go1 (EmbTyPat _ tp) = return $ HsEmbTy noExtField (hstp_to_hswc tp)-      where hstp_to_hswc :: HsTyPat GhcRn -> LHsWcType GhcRn-            hstp_to_hswc (HsTP { hstp_ext = HsTPRn { hstp_nwcs = wcs }, hstp_body = hs_ty })-                        = HsWC { hswc_ext = wcs, hswc_body = hs_ty }+    go1 (EmbTyPat _ _tp) = panic "tcPatToExpr: invalid type pattern"     go1 (InvisPat _ _tp) = panic "tcPatToExpr: invalid invisible pattern"     go1 (XPat (HsPatExpanded _ pat))= go1 pat @@ -1079,8 +1096,12 @@     go1 p@(NPlusKPat {})                     = notInvertible p     go1 p@(OrPat {})                         = notInvertible p -    notInvertible p = Left (PatSynNotInvertible p)+    notInvertible p = invalidRhs (PatSynNotInvertible p) +-- See Note [Discarding types in the builder expression]+wildCardTyArg :: LHsExpr GhcRn+wildCardTyArg = wrapGenSpan (HsHole (HoleVar (wrapGenSpan unnamedHoleRdrName)))+ {- Note [Builder for a bidirectional pattern synonym] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For a bidirectional pattern synonym, the function 'tcPatToExpr'@@ -1151,9 +1172,17 @@ or         g (K (Just True) False) = ... -Note [Type signatures and the builder expression]+Note [Discarding types in the builder expression] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+The RHS of an implicitly bidirectional pattern synonym may mention types in+three ways: a pattern signature (p :: ty), an invisible type argument (@ty),+and a required type argument (type ty).  Required type arguments may be obscured+by the omission of the `type` keyword.++A type may /bind/ variables when it occurs in a pattern, and those binders have+no counterpart in the builder's scope, so tcPatToExpr must not carry them over. Consider+    pattern L x = Left x :: Either [a] [b]  In tc{Infer/Check}PatSynDecl we will check that the pattern has the@@ -1170,6 +1199,71 @@ latter; #9867.)  No, the job of the signature is done, so when converting the pattern to an expression (for the builder RHS) we simply discard the signature.++The same reasoning applies to the other two forms, but the way we discard+them differs.  Which form an argument takes is not apparent from the pattern+alone: in++     pattern P x = MkT a x++'a' looks like an ordinary variable pattern, and only the TyVarBinders in+MkT's type say that it stands in a required type argument position.  We get+those binders from the typechecked ConLike, via conLikeUserTyVarBinders, so+mkPrefixConExpr must look the constructor up before it can walk the arguments.+It then lines them up against the binders with zipPatsBndrs, as described+in Note [Zipping ConPat arguments with TyVarBinders] in GHC.Tc.Gen.Pat.++Each argument is then treated accordingly:++* Invisible type arguments (@ty) are dropped from the argument list+  altogether.  Given++     pattern Q x = MkT @a x++  the builder is $bQ x = MkT x.  Dropping is safe because the argument+  instantiates either a universal, which the expected type of the builder+  already pins down, or an existential, which cannot take a concrete type+  in a pattern anyway. Improper handling of type arguments led to #27440.++* Required type arguments cannot be dropped, as that would change the syntactic+  arity of the application. Instead, we replace them with wildcards `_`, the+  equivalent of @_ for invisible type arguments.  Given++     pattern R x = MkT (type a) x+     pattern P x = MkT a x++  the builders are $bR x = MkT _ x and $bP x = MkT _ x, and the wildcard is+  solved from the expected type.  Retaining the type would mention a binder that+  is not in scope in the builder (#27583).++This reasoning holds when the RHS is a data constructor.  Two caveats:++* With a helper pattern synonym we can construct an example where discarding+  the type argument rejects an otherwise valid program:++      pattern Q :: forall a. Show a => Int -> S   -- 'a' is ambiguous+      pattern P n = Q @Bool n     -- rejected: $bP n = Q n, ambiguous 'a'++  The example introduces an ambiguous type variable occurring in a class+  constraint.  Such a variable serves no purpose, so we do not expect to+  encounter this problem in practice.  The workaround is to declare P+  explicitly bidirectional and write the builder by hand.++* A required type argument that binds a variable yields a suboptimal error+  message: we fail to solve the wildcard, where we would rather report that 'a'+  is not bound on the LHS.++      data S where MkS :: forall a -> Show a => Int -> S+      pattern P n = MkS a n       -- $bP n = MkS _ n, ambiguous wildcard++  Mind you, the program is rejected either way: it is not possible to bind 'a' on+  the LHS until pattern synonyms support RequiredTypeArguments (#23704) or+  TypeAbstractions (#27642).++We will have to revisit this design once we do add support for those extensions+in pattern synonym declarations (#23704, #27642).  When type variables can be+bound on the LHS, the builder has a scope for them, and discarding every type in+the RHS is no longer the obvious thing to do.  Note [Record PatSyn Desugaring] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
GHC/Tc/Types.hs view
@@ -576,8 +576,8 @@           -- ^ Allows us to choose unique DFun names.          tcg_zany_n :: TcRef Integer,-          -- ^ A source of unique identities for ZonkAny instances-          -- See Note [Any types] in GHC.Builtin.Types, wrinkle (Any4)+          -- ^ A source of unique identities for UnusedType instances+          -- See Note [The types Any and UnusedType] in GHC.Builtin.Types, wrinkle (Any6)          tcg_merged :: [(Module, Fingerprint)],           -- ^ The requirements we merged with; we always have to recompile
GHC/Tc/Types/Evidence.hs view
@@ -58,6 +58,7 @@ import GHC.Core import GHC.Core.Coercion.Axiom import GHC.Core.Coercion+import GHC.Core.Utils( mkCast ) import GHC.Core.Ppr ()   -- Instance OutputableBndr TyVar import GHC.Core.Predicate import GHC.Core.Type@@ -206,9 +207,15 @@ (<.>) :: HsWrapper -> HsWrapper -> HsWrapper WpHole    <.> c         = c c         <.> WpHole    = c-WpCast c1 <.> WpCast c2 = WpCast (c1 `mkTransCo` c2)+WpCast c1 <.> WpCast c2 = WpCast (c2 `mkTransCo` c1)   -- If we can represent the HsWrapper as a cast, try to do so: this may avoid   -- unnecessary eta-expansion (see 'mkWpFun').+  --+  -- NB: <.> behaves like function composition:+  --+  --   WpCast c1 <.> WpCast c2 :: coercionLKind c2 ~> coercionRKind c1+  --+  -- This is thus the same as WpCast (c2 ; c1) and not WpCast (c1 ; c2). c1        <.> c2        = c1 `WpCompose` c2  -- | Smart constructor to create a 'WpFun' 'HsWrapper', which avoids introducing@@ -560,7 +567,7 @@   | assertPpr (coercionRole co == Representational)               (vcat [text "Coercion of wrong role passed to evCastE:", ppr ee, ppr co]) $     isReflCo co = ee-  | otherwise   = Cast ee co+  | otherwise   = mkCast ee co  evDFunApp :: DFunId -> [Type] -> [EvExpr] -> EvTerm -- Dictionary instance application, including when the "dictionary function"
GHC/Tc/Types/Origin.hs view
@@ -24,6 +24,7 @@   pprCtOrigin, pprCtOriginBriefly,   isGivenOrigin, isWantedWantedFunDepOrigin,   isWantedSuperclassOrigin,+  foldMapCtOrigin, isHasFieldOrigin,   ClsInstOrQC(..), NakedScFlag(..), NonLinearPatternReason(..),   HsImplicitLiftSplice(..),   StandaloneDeriv,@@ -59,6 +60,8 @@  import GHC.Hs +import GHC.Builtin.Names (getFieldName)+ import GHC.Core.DataCon import GHC.Core.ConLike import GHC.Core.TyCon@@ -88,6 +91,7 @@  import qualified Data.Kind as Hs import Data.List.NonEmpty (NonEmpty (..))+import qualified Data.Semigroup as Semi  {- ********************************************************************* *                                                                      *@@ -744,7 +748,7 @@ exprCtOrigin (OpApp _ _ op _)     = lexprCtOrigin op exprCtOrigin (NegApp _ e _)       = lexprCtOrigin e exprCtOrigin (HsPar _ e)          = lexprCtOrigin e-exprCtOrigin (HsProjection _ _)   = SectionOrigin+exprCtOrigin (HsProjection _ (f :| _)) = GetFieldOrigin (field_label $ unLoc $ dfoLabel f) exprCtOrigin (SectionL _ _ _)     = SectionOrigin exprCtOrigin (SectionR _ _ _)     = SectionOrigin exprCtOrigin (ExplicitTuple {})   = Shouldn'tHappenOrigin "explicit tuple"@@ -1000,7 +1004,93 @@ pprNonLinearPatternReason ViewPatternReason = parens (text "view patterns aren't linear") pprNonLinearPatternReason OtherPatternReason = empty +{- *********************************************************************+*                                                                      *+                     Recursing through CtOrigin+*                                                                      *+********************************************************************* -} +-- | Fold over a 'CtOrigin', looking through all recursive+-- occurrences of 'CtOrigin' within 'CtOrigin'.+foldMapCtOrigin :: forall m. Semigroup m => (CtOrigin -> m) -> CtOrigin -> m+foldMapCtOrigin f = go+  where+    go :: CtOrigin -> m+    go orig =+      case orig of+        KindEqOrigin _ _ o _ -> recur o+        CycleBreakerOrigin o -> recur o+        WantedSuperclassOrigin _ o -> recur o+        ScOrigin cls_or_qc _sc_flag ->+          case cls_or_qc of+            IsQC _ o -> recur o+            IsClsInst -> f orig+        FunDepOrigin1 _ o1 _ _ o2 _ -> f orig Semi.<> go o1 Semi.<> go o2+        FunDepOrigin2 _ o _ _ -> recur o+        InjTFOrigin1 _ o1 _ _ o2 _ -> f orig Semi.<> go o1 Semi.<> go o2++        -- Explicit pattern match on remaining constructors, in order to get+        -- better pattern-match warnings when constructors are changed or+        -- added/removed. This isn't entirely fool-proof, as someone may still+        -- change the type of one of the fields and hide a 'CtOrigin' inside.+        --+        -- This approach was chosen instead of using 'syb'/'GHC.Generics',+        -- because those would require deriving 'Data.Data'/'Generic' on+        -- a huge number of datatypes.+        GivenOrigin {} -> f orig+        GivenSCOrigin {} -> f orig+        OccurrenceOf {} -> f orig+        OccurrenceOfRecSel {} -> f orig+        AppOrigin {} -> f orig+        SpecPragOrigin {} -> f orig+        TypeEqOrigin {}-> f orig+        IPOccOrigin {} -> f orig+        OverLabelOrigin {} -> f orig+        LiteralOrigin {} -> f orig+        NegateOrigin {} -> f orig+        ArithSeqOrigin {} -> f orig+        AssocFamPatOrigin {} -> f orig+        SectionOrigin {} -> f orig+        GetFieldOrigin {} -> f orig+        TupleOrigin {} -> f orig+        ExprSigOrigin {} -> f orig+        PatSigOrigin {} -> f orig+        PatOrigin {} -> f orig+        ProvCtxtOrigin {} -> f orig+        RecordUpdOrigin {} -> f orig+        ViewPatOrigin {} -> f orig+        DerivOrigin {} -> f orig+        DerivOriginDC {} -> f orig+        DerivOriginCoerce {}  -> f orig+        DefaultOrigin {} -> f orig+        DoOrigin {} -> f orig+        DoPatOrigin {} -> f orig+        MCompOrigin {} -> f orig+        MCompPatOrigin {} -> f orig+        ProcOrigin {} -> f orig+        ArrowCmdOrigin {} -> f orig+        AnnOrigin {} -> f orig+        ExprHoleOrigin {} -> f orig+        TypeHoleOrigin {} -> f orig+        PatCheckOrigin {} -> f orig+        ListOrigin {} -> f orig+        IfThenElseOrigin {} -> f orig+        BracketOrigin {} -> f orig+        StaticOrigin {} -> f orig+        ImpedanceMatching {} -> f orig+        Shouldn'tHappenOrigin {} -> f orig+        InstProvidedOrigin {} -> f orig+        NonLinearPatternOrigin {} -> f orig+        OmittedFieldOrigin {} -> f orig+        UsageEnvironmentOf {} -> f orig+        FRROrigin {} -> f orig+        InstanceSigOrigin {} -> f orig+        AmbiguityCheckOrigin {} -> f orig+        ImplicitLiftOrigin {} -> f orig++      where+        recur o = f orig Semi.<> go o+ {- ********************************************************************* *                                                                      *              CallStacks and CtOrigin@@ -1025,6 +1115,30 @@   --      but we can perhaps improve it in the light of user feedback   where     orig_fs = mkFastString (showSDocUnsafe (pprCtOriginBriefly orig))++{- *********************************************************************+*                                                                      *+                       HasField and CtOrigin+*                                                                      *+********************************************************************* -}++-- | Does this constraint arise from GHC internal mechanisms that desugar to+-- usage of the 'HasField' typeclass (e.g. OverloadedRecordDot, etc)?+--+-- Used to avoid emitting a poor "incomplete record selector" warning directly+-- in typechecker, in cases when the desugarer will be able to emit a better+-- error message, due to having better pattern match checking information.+-- See (IRS7) in Note [Detecting incomplete record selectors]+-- in GHC.HsToCore.Pmc+isHasFieldOrigin :: CtOrigin -> Bool+isHasFieldOrigin = Semi.getAny . foldMapCtOrigin (Semi.Any . go)+  where+    go orig = case orig of+      OccurrenceOf n -> n == getFieldName+      OccurrenceOfRecSel {} -> True+      GetFieldOrigin {} -> True+      RecordUpdOrigin {} -> True+      _ -> False  {- ************************************************************************
GHC/Tc/Utils/Env.hs view
@@ -8,6 +8,7 @@                                       -- in module Language.Haskell.Syntax.Extension {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE LambdaCase #-}+{-# LANGUAGE MultiWayIf #-}  module GHC.Tc.Utils.Env(         TyThing(..), TcTyThing(..), TcId,@@ -138,7 +139,7 @@ import qualified GHC.LanguageExtensions as LangExt  import GHC.Iface.Errors.Types-import GHC.Rename.Unbound ( unknownNameSuggestions )+import GHC.Rename.Unbound ( unknownNameSuggestions, mkUnboundGREName ) import GHC.Tc.Errors.Types.PromotionErr import {-# SOURCE #-} GHC.Tc.Errors.Hole (getHoleFitDispConfig) @@ -234,7 +235,7 @@   = addLocM tcLookupGlobal name  tcLookupGlobal :: Name -> TcM TyThing--- The Name is almost always an ExternalName, but not always+-- The Name is almost always an ExternalName, but not always: -- In GHCi, we may make command-line bindings (ghci> let x = True) -- that bind a GlobalId, but with an InternalName tcLookupGlobal name@@ -242,15 +243,12 @@           env <- getGblEnv         ; case lookupNameEnv (tcg_type_env env) name of {                 Just thing -> return thing ;-                Nothing    ->-                 -- Should it have been in the local envt?                 -- (NB: use semantic mod here, since names never use                 -- identity module, see Note [Identity versus semantic module].)-          if nameIsLocalOrFrom (tcg_semantic_mod env) name-          then notFound name  -- Internal names can happen in GHCi-          else-+                Nothing | nameIsLocalOrFrom (tcg_semantic_mod env) name ->+                              notFound $ mkUnboundGREName <$> noUserRdr name  -- Internal names can happen in GHCi+                        | otherwise ->            -- Try home package table and external package table     do  { mb_thing <- tcLookupImported_maybe name         ; case mb_thing of@@ -1210,9 +1208,28 @@ pprBinders [bndr] = quotes (ppr bndr) pprBinders bndrs  = pprWithCommas ppr bndrs -notFound :: Name -> TcM TyThing-notFound name+notFound :: WithUserRdr GlobalRdrElt -> TcM TyThing+notFound (WithUserRdr rdr gre)   = do { lcl_env <- getLclEnv+       ; lvls <- getCurrentAndBindLevel gre+       ; if    -- See Note [Out of scope might be a staging error]+           | isUnboundName name -> failM  -- If the name really isn't in scope+                                          -- don't report it again (#11941)+                                          -- the+                                          -- the 'Nothing' case of 'getCurrentAndBindLevel'+                                          -- currently means 'isUnboundName' but to avoid+                                          -- introducing bugs after a refactoring of that+                                          -- function, we check this completely independently+                                          -- before scrutinizing lvls+           | Just (_top_lvl_flag, bind_lvls, lvl@Splice {}) <- lvls -> failWithTc $+             TcRnBadlyLevelled+               (LevelCheckSplice (WithUserRdr rdr gre))+               bind_lvls+               (thLevelIndex lvl)+               Nothing+               ErrorWithoutFlag+           | otherwise  -> pure ()+        ; if isTermVarOrFieldNameSpace (nameNameSpace name)            then                -- This code path is only reachable with RequiredTypeArguments enabled@@ -1235,6 +1252,7 @@                   -- so let's just not print it!  Getting a loop here is                   -- very unhelpful, because it hides one compiler bug with another        }+       where name = greName gre  wrongThingErr :: WrongThingSort -> TcTyThing -> Name -> TcM a wrongThingErr expected thing name =@@ -1243,14 +1261,23 @@ {- Note [Out of scope might be a staging error] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider-  x = 3-  data T = MkT $(foo x)+  type T = Int+  foo = $(1 :: T) -where 'foo' is imported from somewhere.+GHC currently leaves the user some liberty when it comes to using+types in a manner that is theoretically not well-staged.+E.g. if `T` here were to be a value, we would reject the program with+a staging error. Since it is a type though, we allow it for backwards+compatibility reasons. -This is really a staging error, because we can't run code involving 'x'.-But in fact the type checker processes types first, so 'x' won't even be-in the type envt when we look for it in $(foo x).  So inside splices we-report something missing from the type env as a staging error.-See #5752 and #5795.+However, in this case, we're just in the process of renaming a splice+when trying to type check an expression involving a type, that hasn't+even been added to the (type checking) environment yet. That is, why+it is out of scope.++The reason why we cannot recognise this issue earlier is, that if we+are not actually type checking the splice, i.e. if we're only using the+name of the type (e.g. ''T), the program should be accepted.++We stop and report a staging error. -}
GHC/Tc/Utils/Instantiate.hs view
@@ -13,7 +13,6 @@ module GHC.Tc.Utils.Instantiate (      topSkolemise, skolemiseRequired,      topInstantiate,-     instantiateSigma,      instCall, instDFunType, instStupidTheta, instTyVarsWith,      newWanted, newWanteds, @@ -81,7 +80,6 @@ import GHC.Types.Var.Env import GHC.Types.Id import GHC.Types.Name-import GHC.Types.Name.Env import GHC.Types.Name.Reader (WithUserRdr(..)) import GHC.Types.Var import qualified GHC.LanguageExtensions as LangExt@@ -283,62 +281,39 @@ -- NB: returns a type with no (=>), --     and no invisible forall at the top topInstantiate orig sigma-  | (tvs,   body1) <- tcSplitSomeForAllTyVars isInvisibleForAllTyFlag sigma-  , (theta, body2) <- tcSplitPhiTy body1+  | (tvs,   phi_ty)  <- tcSplitSomeForAllTyVars isInvisibleForAllTyFlag sigma+  , (theta, body_ty) <- tcSplitPhiTy phi_ty   , not (null tvs && null theta)-  = do { (_, wrap1, body3) <- instantiateSigma orig noConcreteTyVars tvs theta body2-           -- Why 'noConcreteTyVars' here?+  = do { (subst, inst_tvs) <- newMetaTyVarsX empty_subst tvs+           -- No need to worry about concrete tyvars here (c.f. instantiateSigma)            -- See Note [Representation-polymorphism checking built-ins]            -- in GHC.Tc.Utils.Concrete. -       -- Loop, to account for types like-       --       forall a. Num a => forall b. Ord b => ...-       ; (wrap2, body4) <- topInstantiate orig body3--       ; return (wrap2 <.> wrap1, body4) }+       ; let inst_theta = substTheta subst theta+             inst_body  = substTy subst body_ty -  | otherwise = return (idHsWrapper, sigma)+       ; wrap1 <- instCall orig (mkTyVarTys inst_tvs) inst_theta -instantiateSigma :: CtOrigin-                 -> ConcreteTyVars -- ^ concreteness information-                 -> [TyVar]-                 -> TcThetaType -> TcSigmaType-                 -> TcM ([TcTyVar], HsWrapper, TcSigmaType)--- (instantiate orig tvs theta ty)--- instantiates the type variables tvs, emits the (instantiated)--- constraints theta, and returns the (instantiated) type ty-instantiateSigma orig concs tvs theta body_ty-  = do { rec (subst, inst_tvs) <- mapAccumLM (new_meta subst) empty_subst tvs-       ; let inst_theta  = substTheta subst theta-             inst_body   = substTy subst body_ty-             inst_tv_tys = mkTyVarTys inst_tvs+       -- Loop, to account for types like+       --       forall a. Num a => forall b. Ord b => ...+       ; (wrap2, inner_body) <- topInstantiate orig inst_body -       ; wrap <- instCall orig inst_tv_tys inst_theta-       ; traceTc "Instantiating"+       ; traceTc "topInstantiate"                  (vcat [ text "origin" <+> pprCtOrigin orig                        , text "tvs"   <+> ppr tvs                        , text "theta" <+> ppr theta                        , text "type" <+> debugPprType body_ty-                       , text "with" <+> vcat (map debugPprType inst_tv_tys)+                       , text "with" <+> ppr inst_tvs                        , text "theta:" <+> ppr inst_theta ]) -      ; return (inst_tvs, wrap, inst_body) }+      ; return (wrap2 <.> wrap1, inner_body) }++  | otherwise+  = return (idHsWrapper, sigma)+   where-    in_scope = mkInScopeSet (tyCoVarsOfType (mkSpecSigmaTy tvs theta body_ty))-               -- mkSpecSigmaTy: Inferred vs Specified is not important here;-               --                We just want an accurate free-var set-    empty_subst = mkEmptySubst in_scope-    new_meta :: Subst -> Subst -> TyVar -> TcM (Subst, TcTyVar)-    new_meta final_subst subst tv-      -- Is this a type variable that must be instantiated to a concrete type?-      -- If so, create a ConcreteTv metavariable instead of a plain TauTv.-      -- See Note [Representation-polymorphism checking built-ins] in GHC.Tc.Utils.Concrete.-      | Just conc_orig0 <- lookupNameEnv concs (tyVarName tv)-      , let conc_orig = substConcreteTvOrigin final_subst body_ty conc_orig0-      -- See Note [substConcreteTvOrigin].-      = newConcreteTyVarX conc_orig subst tv-      | otherwise-      = newMetaTyVarX subst tv+    empty_subst = mkEmptySubst (mkInScopeSet (tyCoVarsOfType sigma))+  instTyVarsWith :: CtOrigin -> [TyVar] -> [TcType] -> TcM Subst -- Use this when you want to instantiate (forall a b c. ty) with
GHC/Tc/Utils/Monad.hs view
@@ -146,7 +146,7 @@   getCCIndexM, getCCIndexTcM,    -- * Zonking-  liftZonkM, newZonkAnyType,+  liftZonkM, newUnusedType,    -- * Complete matches   localAndImportedCompleteMatches, getCompleteMatchesTcM,@@ -160,7 +160,7 @@   import GHC.Builtin.Names-import GHC.Builtin.Types( zonkAnyTyCon )+import GHC.Builtin.Types( unusedTypeTyCon )  import GHC.Tc.Errors.Types import GHC.Tc.Types     -- Re-export all@@ -186,7 +186,7 @@ import GHC.Core.Multiplicity import GHC.Core.InstEnv import GHC.Core.FamInstEnv-import GHC.Core.Type( mkNumLitTy )+import GHC.Core.Type( mkStrLitTy )  import GHC.Driver.Env import GHC.Driver.Env.KnotVars@@ -1865,17 +1865,24 @@      ; writeTcRef dfun_n_var (extendOccSet set occ)      ; return occ } -newZonkAnyType :: Kind -> TcM Type--- Return a type (ZonkAny @k n), where n is fresh--- Recall  ZonkAny :: forall k. Natural -> k--- See Note [Any types] in GHC.Builtin.Types, wrinkle (Any4)-newZonkAnyType kind+newUnusedType :: Name -> Kind -> TcM Type+-- Return a type (UnusedType @k sym_n), where sym+-- is a name and n is a fresh Integer.+-- Recall  UnusedType :: forall k. Symbol -> k+-- See Note [The types Any and UnusedType] in GHC.Builtin.Types, wrinkle (Any6)+newUnusedType name kind   = do { env <- getGblEnv        ; let zany_n_var = tcg_zany_n env        ; i <- readTcRef zany_n_var        ; let !i2 = i+1        ; writeTcRef zany_n_var i2-       ; return (mkTyConApp zonkAnyTyCon [kind, mkNumLitTy i]) }+       -- Mind that the "_" here is load-bearing:+       -- name foo1 with zany_n_var = 1 musn't be equal to+       -- name foo with zany_n_var = 11 b/c that way the Pmc+       -- would consider them equal. Using "_" suffices because+       -- numbers never start with _ and so (legal) identfiers like+       -- foo_ would become foo__1 which is distinct from e.g. foo_1+       ; return (mkTyConApp unusedTypeTyCon [kind, mkStrLitTy $ getOccFS name `appendFS` fsLit "_" `appendFS` fsLit (show i) ]) }  getConstraintVar :: TcM (TcRef WantedConstraints) getConstraintVar = do { env <- getLclEnv; return (tcl_lie env) }@@ -2166,32 +2173,22 @@ getThLevel :: TcM ThLevel getThLevel = do { env <- getLclEnv; return (getLclEnvThLevel env) } -getCurrentAndBindLevel :: Name -> TcRn (Maybe (TopLevelFlag, Set.Set ThLevelIndex, ThLevel))-getCurrentAndBindLevel name+getCurrentAndBindLevel :: GlobalRdrElt -> TcRn (Maybe (TopLevelFlag, Set.Set ThLevelIndex, ThLevel))+getCurrentAndBindLevel gre   = do { env <- getLclEnv;-       ; case lookupNameEnv (getLclEnvThBndrs env) name of-           Nothing                  -> do-              lvls <- getExternalBindLvl name-              if Set.empty == lvls-                -- This case happens when code is generated for identifiers which are not-                -- in scope.-                ---                -- TODO: What happens if someone generates [|| GHC.Magic.dataToTag# ||]-                then do-                  return Nothing-                else return (Just (TopLevel, lvls, getLclEnvThLevel env))-           Just (top_lvl, bind_lvl) -> return (Just (top_lvl, Set.singleton bind_lvl, getLclEnvThLevel env)) }+       ; return $ case lookupNameEnv (getLclEnvThBndrs env) $ greName gre  of+           Nothing+             | Set.null lvls  -> Nothing+             -- This case happens when code is generated for identifiers which are not+             -- in scope.+             --+             -- TODO: What happens if someone generates [|| GHC.Magic.dataToTag# ||]+             | otherwise -> Just (TopLevel, lvls, getLclEnvThLevel env)+           Just (top_lvl, bind_lvl) -> Just (top_lvl, Set.singleton bind_lvl, getLclEnvThLevel env) }+  where lvls = getExternalBindLvl gre -getExternalBindLvl :: Name -> TcRn (Set.Set ThLevelIndex)-getExternalBindLvl name = do-  env <- getGlobalRdrEnv-  mod <- getModule-  case lookupGRE_Name env name of-    Just gre -> return $ (Set.map thLevelIndexFromImportLevel (greLevels gre))-    Nothing ->-      if nameIsLocalOrFrom mod name-        then return $ Set.singleton topLevelIndex-        else return Set.empty+getExternalBindLvl :: GlobalRdrElt -> Set.Set ThLevelIndex+getExternalBindLvl gre = Set.map thLevelIndexFromImportLevel (greLevels gre)  setThLevel :: ThLevel -> TcM a -> TcRn a setThLevel l = updLclEnv (setLclEnvThLevel l)
GHC/Tc/Utils/TcMType.hs view
@@ -25,15 +25,14 @@   newFlexiTyVarTy,              -- Kind -> TcM TcType   newFlexiTyVarTys,             -- Int -> Kind -> TcM [TcType]   newOpenFlexiTyVar, newOpenFlexiTyVarTy, newOpenTypeKind,-  newOpenFlexiFRRTyVar, newOpenFlexiFRRTyVarTy,-  newOpenBoxedTypeKind,+  newOpenFlexiFRRTyVarTy,   newMetaKindVar, newMetaKindVars,   newMetaTyVarTyAtLevel, newConcreteTyVarTyAtLevel, substConcreteTvOrigin,-  newAnonMetaTyVar, newConcreteTyVar,+  newAnonMetaTyVar, newConcreteTyVar, mkConcreteInfo,   cloneMetaTyVar, cloneMetaTyVarWithInfo,   newCycleBreakerTyVar,-   newMultiplicityVar,+   readMetaTyVar, writeMetaTyVar, writeMetaTyVarRef,   newTauTvDetailsAtLevel, newMetaDetails, newMetaTyVarName,   isFilledMetaTyVar_maybe, isFilledMetaTyVar, isUnfilledMetaTyVar,@@ -43,22 +42,19 @@   newEvVar, newEvVars, newDict,   newWantedWithLoc, newWanted, newWanteds, cloneWanted, cloneWC, cloneWantedCtEv,   emitWanted, emitWantedEq, emitWantedEvVar,-  emitWantedEqs,+  emitWantedEqs, emitNewExprHole,   newTcEvBinds, newNoTcEvBinds, addTcEvBind,-  emitNewExprHole, -  newCoercionHole,-  fillCoercionHole, isFilledCoercionHole,+  newCoercionHole, fillCoercionHole, isFilledCoercionHole,   checkCoercionHole,    newImplication,    --------------------------------   -- Instantiation-  newMetaTyVars, newMetaTyVarX, newMetaTyVarsX, newMetaTyVarBndrsX,+  newMetaTyVars, newMetaTyVarX, newMetaTyVarsX,   newMetaTyVarTyVarX,   newTyVarTyVar, cloneTyVarTyVar,-  newConcreteTyVarX,   newPatTyVar, newSkolemTyVar, newWildCardX,    --------------------------------@@ -714,26 +710,29 @@ variables only refer to other type variables, but this restriction was dropped, and ScopedTypeVariables can now refer to full types (GHC Proposal 29).++Note [Name of a unification variable]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+We give unification variables a /System/ Name, which is treated specially+in two ways++* It is eagerly elmininated the the unifier; see+  GHC.Tc.Utils.Unify.nicer_to_update_tv1, and+  GHC.Tc.Solver.Equality.canEqTyVarTyVar (nicer_to_update_tv2)++* It influences the way it is tidied; see TypeRep.tidyTyVarBndr. -}  newMetaTyVarName :: FastString -> TcM Name--- Makes a /System/ Name, which is eagerly eliminated by--- the unifier; see GHC.Tc.Utils.Unify.nicer_to_update_tv1, and--- GHC.Tc.Solver.Equality.canEqTyVarTyVar (nicer_to_update_tv2)+-- Makes a /System/ Name; see Note [Name of a unification variable] newMetaTyVarName str   = newSysName (mkTyVarOccFS str)  cloneMetaTyVarName :: Name -> TcM Name+-- Makes a /System/ Name; see Note [Name of a unification variable] cloneMetaTyVarName name   = newSysName (nameOccName name)-         -- See Note [Name of an instantiated type variable] -{- Note [Name of an instantiated type variable]-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-At the moment we give a unification variable a System Name, which-influences the way it is tidied; see TypeRep.tidyTyVarBndr.--}- metaInfoToTyVarName :: MetaInfo -> FastString metaInfoToTyVarName  meta_info =   case meta_info of@@ -795,18 +794,21 @@                  -> FastString -> TcKind -> TcM TcTyVar newConcreteTyVar reason fs kind   = assertPpr (isConcreteType kind) assert_msg $-  do { th_lvl <- getThLevel-     ; if-        -- See [Wrinkle: Typed Template Haskell]-        -- in Note [hasFixedRuntimeRep] in GHC.Tc.Utils.Concrete.-        | TypedBrack _ <- th_lvl-        -> newNamedAnonMetaTyVar fs TauTv kind--        | otherwise-        -> newNamedAnonMetaTyVar fs (ConcreteTv reason) kind }+  do { info <- mkConcreteInfo reason+     ; newNamedAnonMetaTyVar fs info kind }   where     assert_msg = text "newConcreteTyVar: non-concrete kind" <+> ppr kind +mkConcreteInfo :: ConcreteTvOrigin -> TcM MetaInfo+-- Usually returns (ConcreteTv origin); but if we are in a typed+-- Template Haskell bracket, return TauTv+-- See [Wrinkle: Typed Template Haskell] in Note [hasFixedRuntimeRep] in GHC.Tc.Utils.Concrete+mkConcreteInfo conc_origin+  = do { th_lvl <- getThLevel+       ; case th_lvl of+            TypedBrack {} -> return TauTv+            _             -> return (ConcreteTv conc_origin) }+ newPatTyVar :: Name -> Kind -> TcM TcTyVar newPatTyVar name kind   = do { details <- newMetaDetails TauTv@@ -976,35 +978,18 @@   = do { kind <- newOpenTypeKind        ; newFlexiTyVar kind } --- | Like 'newOpenFlexiTyVar', but ensures the type variable has a+-- | Like 'newOpenFlexiTyVarTy', but ensures the type variable has a -- syntactically fixed RuntimeRep in the sense of Note [Fixed RuntimeRep] -- in GHC.Tc.Utils.Concrete.-newOpenFlexiFRRTyVar :: FixedRuntimeRepContext -> TcM TcTyVar-newOpenFlexiFRRTyVar frr_ctxt-  = do { th_lvl <- getThLevel-       ; case th_lvl of-          { TypedBrack _ -- See [Wrinkle: Typed Template Haskell]-              -> newOpenFlexiTyVar -- in Note [hasFixedRuntimeRep] in GHC.Tc.Utils.Concrete.-          ; _ ->-   mdo { let conc_orig = ConcreteFRR $+newOpenFlexiFRRTyVarTy :: FixedRuntimeRepContext -> TcM TcType+newOpenFlexiFRRTyVarTy frr_ctxt+  = mdo { let conc_orig = ConcreteFRR $                           FixedRuntimeRepOrigin                             { frr_context = frr_ctxt                             , frr_type    = mkTyVarTy tv }-        ; rr <- mkTyVarTy <$> newConcreteTyVar conc_orig (fsLit "cx") runtimeRepTy-        ; tv <- newFlexiTyVar (mkTYPEapp rr)-        ; return tv } } }---- | See 'newOpenFlexiFRRTyVar'.-newOpenFlexiFRRTyVarTy :: FixedRuntimeRepContext -> TcM TcType-newOpenFlexiFRRTyVarTy frr_ctxt-  = do { tv <- newOpenFlexiFRRTyVar frr_ctxt-       ; return (mkTyVarTy tv) }--newOpenBoxedTypeKind :: TcM TcKind-newOpenBoxedTypeKind-  = do { lev <- newFlexiTyVarTy (mkTyConTy levityTyCon)-       ; let rr = mkTyConApp boxedRepDataConTyCon [lev]-       ; return (mkTYPEapp rr) }+        ; rr_tv <- newConcreteTyVar conc_orig (fsLit "cx") runtimeRepTy+        ; tv <- newFlexiTyVar (mkTYPEapp (mkTyVarTy rr_tv))+        ; return (mkTyVarTy tv) }  newMetaTyVars :: [TyVar] -> TcM (Subst, [TcTyVar]) -- Instantiate with META type variables@@ -1020,33 +1005,14 @@ -- Just like newMetaTyVars, but start with an existing substitution. newMetaTyVarsX subst = mapAccumLM newMetaTyVarX subst -newMetaTyVarBndrsX :: Subst -> [VarBndr TyVar vis] -> TcM (Subst, [VarBndr TcTyVar vis])-newMetaTyVarBndrsX subst bndrs = do-  (subst, bndrs') <- newMetaTyVarsX subst (binderVars bndrs)-  pure (subst, zipWith mkForAllTyBinder flags bndrs')-  where-    flags = binderFlags bndrs- newMetaTyVarX :: Subst -> TyVar -> TcM (Subst, TcTyVar) -- Make a new unification variable tyvar whose Name and Kind come from -- an existing TyVar. We substitute kind variables in the kind. newMetaTyVarX = new_meta_tv_x TauTv --- | Like 'newMetaTyVarX', but for concrete type variables.-newConcreteTyVarX :: ConcreteTvOrigin -> Subst -> TyVar -> TcM (Subst, TcTyVar)-newConcreteTyVarX conc subst tv-  = do { th_lvl <- getThLevel-       ; if-          -- See [Wrinkle: Typed Template Haskell]-          -- in Note [hasFixedRuntimeRep] in GHC.Tc.Utils.Concrete.-          | TypedBrack _  <- th_lvl-          -> new_meta_tv_x TauTv subst tv-          | otherwise-          -> new_meta_tv_x (ConcreteTv conc) subst tv }- newMetaTyVarTyVarX :: Subst -> TyVar -> TcM (Subst, TcTyVar) -- Just like newMetaTyVarX, but make a TyVarTv-newMetaTyVarTyVarX subst tv = new_meta_tv_x TyVarTv subst tv+newMetaTyVarTyVarX = new_meta_tv_x TyVarTv  newWildCardX :: Subst -> TyVar -> TcM (Subst, TcTyVar) newWildCardX subst tv
GHC/Tc/Utils/TcType.hs view
@@ -88,7 +88,7 @@   isSigmaTy, isRhoTy, isRhoExpTy, isOverloadedTy,   isFloatingPrimTy, isDoubleTy, isFloatTy, isIntTy, isWordTy, isStringTy,   isIntegerTy, isNaturalTy,-  isBoolTy, isUnitTy, isAnyTy, isZonkAnyTy, isCharTy,+  isBoolTy, isUnitTy, isAnyTy, isUnusedTypeTy, isCharTy,   isTauTy, isTauTyCon, tcIsTyVarTy,   isPredTy, isSimplePredTy, isTyVarClassPred,   checkValidClsArgs, hasTyVarHead,@@ -731,7 +731,7 @@              | QLInstVar   -- See Note [TcLevel invariants] for what this Int is   -- See also Note [TcLevel assignment]-  -- See also Note [The QLInstVar TcLevel]+  -- See also Note [QuickLook instantiation variables]  {- Note [TcLevel invariants]@@ -766,7 +766,7 @@ The level of a MetaTyVar also governs its untouchability.  See Note [Unification preconditions] in GHC.Tc.Utils.Unify. -  -- See also Note [The QLInstVar TcLevel]+  -- See also Note [QuickLook instantiation variables]  Note [TcLevel assignment] ~~~~~~~~~~~~~~~~~~~~~~~~~@@ -777,21 +777,23 @@    2          Second-level implication constraints    ...etc...    QLInstVar  The level for QuickLook instantiation variables-              See Note [The QLInstVar TcLevel]+              See Note [QuickLook instantiation variables] -Note [The QLInstVar TcLevel]-~~~~~~~~~~~~~~~~~~~~~~~~~~~~-QuickLook instantiation variables are identified by having a TcLevel-of QLInstVar.  See Note [Quick Look overview] in GHC.Tc.Gen.App.+Note [QuickLook instantiation variables]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+A QuickLook instantiation variable is identified precisely by+    having a TcLevel of QLInstVar+See (QL1) in Note [Quick Look overview] in GHC.Tc.Gen.App.  The QLInstVar level behaves like infinity: it is greater than any other TcLevel.  See `strictlyDeeperThan` and friends in this module.+ That ensures that we never unify an ordinary unification variable with a QL instantiation variable, e.g.       alpha[tau:3] := Maybe beta[tau:qlinstvar]-(This is an immediate consequence of our general rule that we never+This is an immediate consequence of our general rule that we never unify a variable with a type mentioning deeper variables; the skolem-escape check.)+escape check.  QL instantation variables are eventually turned into ordinary unificaiton variables; see (QL3) in Note [Quick Look overview].@@ -872,14 +874,14 @@ pushTcLevel QLInstVar    = QLInstVar  strictlyDeeperThan :: TcLevel -> TcLevel -> Bool--- See Note [The QLInstVar TcLevel]+-- See Note [QuickLook instantiation variables] strictlyDeeperThan (TcLevel tv_tclvl) (TcLevel ctxt_tclvl)   = tv_tclvl > ctxt_tclvl strictlyDeeperThan QLInstVar (TcLevel {})  = True strictlyDeeperThan _ _                     = False  deeperThanOrSame :: TcLevel -> TcLevel -> Bool--- See Note [The QLInstVar TcLevel]+-- See Note [QuickLook instantiation variables] deeperThanOrSame (TcLevel tv_tclvl) (TcLevel ctxt_tclvl)   = tv_tclvl >= ctxt_tclvl deeperThanOrSame (TcLevel {}) QLInstVar  = False@@ -2038,7 +2040,7 @@     isFloatPrimTy, isDoublePrimTy,     isIntegerTy, isNaturalTy,     isIntTy, isWordTy, isBoolTy,-    isUnitTy, isAnyTy, isZonkAnyTy, isCharTy :: Type -> Bool+    isUnitTy, isAnyTy, isUnusedTypeTy, isCharTy :: Type -> Bool isFloatTy      = is_tc floatTyConKey isDoubleTy     = is_tc doubleTyConKey isFloatPrimTy  = is_tc floatPrimTyConKey@@ -2050,7 +2052,7 @@ isBoolTy       = is_tc boolTyConKey isUnitTy       = is_tc unitTyConKey isAnyTy        = is_tc anyTyConKey-isZonkAnyTy    = is_tc zonkAnyTyConKey+isUnusedTypeTy = is_tc unusedTypeTyConKey isCharTy       = is_tc charTyConKey  -- | Check whether the type is of the form @Any :: k@,
GHC/Tc/Utils/Unify.hs view
@@ -1882,6 +1882,41 @@  See T11305 and T26225 for examples of when this is important. +Wrinkle [Avoiding a loop in tc_sub_type_deep]++  In #26823, we had:++    alpha  <=  a -> alpha++  If we simply unified the two types, the occurs-check would trigger.+  In deep subsumption however, we need to be careful, as we might do the+  following:++    A1. Create fresh metavariables beta, gamma+    A2. Unify alpha ~ beta -> gamma+    A3. Decompose  "beta -> gamma <= a -> (beta -> gamma)", obtaining+              a <= beta  and  gamma <= beta -> gamma+    A4. Recur with gamma <= beta -> gamma++  If we do this, we enter an infinite loop and GHC hangs at compile time.+  To avoid this, we must first recur, before unifying. So the above becomes:++    B1 (like A1). Create fresh metavariables beta, gamma+    B2 (like A3). Decompose  "beta -> gamma <= a -> alpha", obtaining+          a <= beta  and  gamma <= alpha+    B3. Solve these two sub-problems by unification+          a ~ beta,   gamma ~ alpha+    B4 (like A2). Then, and only then, unify alpha ~ beta->gamma++    With this approach, GHC will be left with the following unifications:++      - alpha ~ (beta -> gamma)+      - a ~ beta+      - gamma ~ alpha++    GHC will fail to solve this unification problem due to an occurs check+    failure, thus rejecting the program with a type error (as desired).+ Note [Deep subsumption and required foralls] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ A required forall, (forall a -> ty) behaves like a "rho-type", one with no@@ -2011,8 +2046,9 @@            ; exp_arg  <- newOpenFlexiTyVarTy -- NB: no FRR check needed; we might not need to eta-expand            ; exp_res  <- newOpenFlexiTyVarTy            ; let exp_funTy = FunTy { ft_af = af1, ft_mult = exp_mult, ft_arg = exp_arg, ft_res = exp_res }-           ; unify_wrap <- just_unify exp_funTy ty_e+             -- Recur before unifying; see Wrinkle [Avoiding a loop in tc_sub_type_deep]            ; fun_wrap <- go_fun af1 act_mult act_arg act_res af1 exp_mult exp_arg exp_res+           ; unify_wrap <- just_unify exp_funTy ty_e            ; return $ unify_wrap <.> fun_wrap              -- unify_wrap :: exp_funTy ~> ty_e              -- fun_wrap :: ty_a ~> exp_funTy@@ -2023,9 +2059,9 @@            ; act_arg  <- newOpenFlexiTyVarTy -- NB: no FRR check needed; we might not need to eta-expand            ; act_res  <- newOpenFlexiTyVarTy            ; let act_funTy = FunTy { ft_af = af2, ft_mult = act_mult, ft_arg = act_arg, ft_res = act_res }--           ; unify_wrap <- just_unify ty_a act_funTy+             -- Recur before unifying; see Wrinkle [Avoiding a loop in tc_sub_type_deep]            ; fun_wrap <- go_fun af2 act_mult act_arg act_res af2 exp_mult exp_arg exp_res+           ; unify_wrap <- just_unify ty_a act_funTy            ; return $ fun_wrap <.> unify_wrap              -- unify_wrap :: ty_a ~> act_funTy              -- fun_wrap :: act_funTy ~> ty_e@@ -2093,7 +2129,7 @@                  act_arg_co                  (mkReflCo Nominal act_res)             arg_wrap_frr =-              mkWpCastN (mkSymCo exp_arg_co) <.> arg_wrap <.> mkWpCastN act_arg_co+              mkWpCastN act_arg_co <.> arg_wrap <.> mkWpCastN (mkSymCo exp_arg_co)                --  exp_arg_co :: exp_arg ~> exp_arg_frr                --  act_arg_co :: act_arg ~> act_arg_frr                --  arg_wrap :: exp_arg ~> act_arg
GHC/Tc/Zonk/Type.hs view
@@ -1,4 +1,5 @@ {-# LANGUAGE GADTs #-}+{-# LANGUAGE OverloadedRecordDot #-}  {- (c) The University of Glasgow 2006@@ -48,7 +49,7 @@ import GHC.Tc.TyCl.Build ( TcMethInfo, MethInfo ) import GHC.Tc.Utils.Env ( tcLookupGlobalOnly ) import GHC.Tc.Utils.TcType-import GHC.Tc.Utils.Monad ( newZonkAnyType, setSrcSpanA, liftZonkM, traceTc, addErr )+import GHC.Tc.Utils.Monad ( newUnusedType, setSrcSpanA, liftZonkM, traceTc, addErr ) import GHC.Tc.Types.Evidence import GHC.Tc.Errors.Types import GHC.Tc.Zonk.Env@@ -472,9 +473,9 @@   = do { addErr $ TcRnZonkerMessage (ZonkerCannotDefaultConcrete origin)        ; return (anyTypeOfKind zonked_kind) }   | otherwise-  = do { traceTc "Defaulting flexi tyvar to ZonkAny:" (pprTyVar tv)-          -- See Note [Any types] in GHC.Builtin.Types, esp wrinkle (Any4)-       ; newZonkAnyType zonked_kind }+  = do { traceTc "Defaulting flexi tyvar to UnusedType:" (pprTyVar tv)+          -- See Note [The types Any and UnusedType] in GHC.Builtin.Types, esp wrinkle (Any6)+       ; newUnusedType tv.varName zonked_kind }  zonkCoVarOcc :: CoVar -> ZonkTcM Coercion zonkCoVarOcc cv
GHC/ThToHs.hs view
@@ -998,8 +998,8 @@  cvtPhases :: TH.Phases -> Activation -> Activation cvtPhases AllPhases       dflt = dflt-cvtPhases (FromPhase i)   _    = ActiveAfter NoSourceText i-cvtPhases (BeforePhase i) _    = ActiveBefore NoSourceText i+cvtPhases (FromPhase i)   _    = ActiveAfter  i+cvtPhases (BeforePhase i) _    = ActiveBefore i  cvtRuleBndr :: TH.RuleBndr -> CvtM (Hs.LRuleBndr GhcPs) cvtRuleBndr (RuleVar n)
GHC/Types/Basic.hs view
@@ -84,11 +84,14 @@         DefMethSpec(..),         SwapFlag(..), flipSwap, unSwap, notSwapped, isSwapped, pickSwap, -        CompilerPhase(..), PhaseNum, beginPhase, nextPhase, laterPhase,+        CompilerPhase(..),+        PhaseNum, nextPhase,+        latestPhase, earliestPhase, -        Activation(..), isActive, competesWith,+        Activation(..), isActiveInPhase, competesWith,         isNeverActive, isAlwaysActive, activeInFinalPhase, activeInInitialPhase,         activateAfterInitial, activateDuringFinal, activeAfter,+        beginPhase, endPhase, laterThanPhase,          RuleMatchInfo(..), isConLike, isFunLike,         InlineSpec(..), noUserInlineSpec,@@ -1464,90 +1467,130 @@ The phase sequencing is done by GHC.Opt.Simplify.Driver -} --- | Phase Number-type PhaseNum = Int  -- Compilation phase-                     -- Phases decrease towards zero-                     -- Zero is the last phase+-- | Compilation phase number, as can be written by users in INLINE pragmas,+-- SPECIALISE pragmas, and RULES.+--+--   - phases decrease towards zero+--   - zero is the last phase+--+-- Does not include GHC internal "initial" and "final" phases; see 'CompilerPhase'.+type PhaseNum = Int +-- | Compilation phase number, including the user-specifiable 'PhaseNum'+-- and the GHC internal "initial" and "final" phases. data CompilerPhase-  = InitialPhase    -- The first phase -- number = infinity!-  | Phase PhaseNum  -- User-specificable phases-  | FinalPhase      -- The last phase  -- number = -infinity!-  deriving Eq+  = InitialPhase    -- ^ The first phase; number = infinity!+  | Phase PhaseNum  -- ^ User-specifiable phases+  | FinalPhase      -- ^ The last phase; number = -infinity!+  deriving (Eq, Data)  instance Outputable CompilerPhase where    ppr (Phase n)    = int n-   ppr InitialPhase = text "InitialPhase"-   ppr FinalPhase   = text "FinalPhase"+   ppr InitialPhase = text "initial"+   ppr FinalPhase   = text "final" --- See Note [Pragma source text]+-- | An activation is a range of phases throughout which something is active+-- (like an INLINE pragma, SPECIALISE pragma, or RULE). data Activation   = AlwaysActive-  | ActiveBefore SourceText PhaseNum  -- Active only *strictly before* this phase-  | ActiveAfter  SourceText PhaseNum  -- Active in this phase and later-  | FinalActive                       -- Active in final phase only+  -- | Active only *strictly before* this phase+  | ActiveBefore PhaseNum+  -- | Active in this phase and later phases+  | ActiveAfter  PhaseNum+  -- | Active in the final phase only+  | FinalActive   | NeverActive   deriving( Eq, Data )     -- Eq used in comparing rules in GHC.Hs.Decls  beginPhase :: Activation -> CompilerPhase--- First phase in which the Activation is active--- or FinalPhase if it is never active+-- ^ First phase in which the 'Activation' is active,+-- or 'FinalPhase' if it is never active beginPhase AlwaysActive      = InitialPhase beginPhase (ActiveBefore {}) = InitialPhase-beginPhase (ActiveAfter _ n) = Phase n+beginPhase (ActiveAfter n)   = Phase n beginPhase FinalActive       = FinalPhase beginPhase NeverActive       = FinalPhase +endPhase :: Activation -> CompilerPhase+-- ^ Last phase in which the 'Activation' is active,+-- or 'InitialPhase' if it is never active+endPhase AlwaysActive       = FinalPhase+endPhase (ActiveBefore n)   =+  if nextPhase InitialPhase == Phase n+  then InitialPhase+  else Phase $ n + 1+endPhase (ActiveAfter {})   = FinalPhase+endPhase FinalActive        = FinalPhase+endPhase NeverActive        = InitialPhase+ activeAfter :: CompilerPhase -> Activation--- (activeAfter p) makes an Activation that is active in phase p and after--- Invariant: beginPhase (activeAfter p) = p+-- ^ @activeAfter p@ makes an 'Activation' that is active in phase @p@ and after+--+-- Invariant: @beginPhase (activeAfter p) = p@ activeAfter InitialPhase = AlwaysActive-activeAfter (Phase n)    = ActiveAfter NoSourceText n+activeAfter (Phase n)    = ActiveAfter n activeAfter FinalPhase   = FinalActive  nextPhase :: CompilerPhase -> CompilerPhase--- Tells you the next phase after this one--- Currently we have just phases [2,1,0,FinalPhase,FinalPhase,...]--- Where FinalPhase means GHC's internal simplification steps+-- ^ Tells you the next phase after this one+--+-- Currently we have just phases @[2,1,0,FinalPhase,FinalPhase,...]@,+-- where FinalPhase means GHC's internal simplification steps -- after all rules have run nextPhase InitialPhase = Phase 2 nextPhase (Phase 0)    = FinalPhase nextPhase (Phase n)    = Phase (n-1) nextPhase FinalPhase   = FinalPhase -laterPhase :: CompilerPhase -> CompilerPhase -> CompilerPhase--- Returns the later of two phases-laterPhase (Phase n1)   (Phase n2)   = Phase (n1 `min` n2)-laterPhase InitialPhase p2           = p2-laterPhase FinalPhase   _            = FinalPhase-laterPhase p1           InitialPhase = p1-laterPhase _            FinalPhase   = FinalPhase+earliestPhase :: CompilerPhase -> CompilerPhase -> CompilerPhase+-- ^ Returns the earliest of two phases+earliestPhase (Phase n1)   (Phase n2)   = Phase (n1 `max` n2)+earliestPhase InitialPhase _            = InitialPhase+earliestPhase FinalPhase   p2           = p2+earliestPhase _            InitialPhase = InitialPhase+earliestPhase p1           FinalPhase   = p1 +latestPhase :: CompilerPhase -> CompilerPhase -> CompilerPhase+-- ^ Returns the latest of two phases+latestPhase (Phase n1)   (Phase n2)   = Phase (n1 `min` n2)+latestPhase InitialPhase p2           = p2+latestPhase FinalPhase   _            = FinalPhase+latestPhase p1           InitialPhase = p1+latestPhase _            FinalPhase   = FinalPhase++-- | @p1 `laterThanOrEqualPhase` p2@ computes whether @p1@ happens (strictly)+-- after @p2@.+laterThanPhase :: CompilerPhase -> CompilerPhase -> Bool+p1 `laterThanPhase` p2 = toNum p1 < toNum p2+  where+    toNum :: CompilerPhase -> Int+    toNum InitialPhase = maxBound+    toNum (Phase i)    = i+    toNum FinalPhase   = minBound+ activateAfterInitial :: Activation--- Active in the first phase after the initial phase+-- ^ Active in the first phase after the initial phase activateAfterInitial = activeAfter (nextPhase InitialPhase)  activateDuringFinal :: Activation--- Active in the final simplification phase (which is repeated)+-- ^ Active in the final simplification phase (which is repeated) activateDuringFinal = FinalActive -isActive :: CompilerPhase -> Activation -> Bool-isActive InitialPhase act = activeInInitialPhase act-isActive (Phase p)    act = activeInPhase p act-isActive FinalPhase   act = activeInFinalPhase act+isActiveInPhase :: CompilerPhase -> Activation -> Bool+isActiveInPhase InitialPhase act = activeInInitialPhase act+isActiveInPhase (Phase p)    act = activeInPhase p act+isActiveInPhase FinalPhase   act = activeInFinalPhase act  activeInInitialPhase :: Activation -> Bool-activeInInitialPhase AlwaysActive      = True-activeInInitialPhase (ActiveBefore {}) = True-activeInInitialPhase _                 = False+activeInInitialPhase act = beginPhase act == InitialPhase  activeInPhase :: PhaseNum -> Activation -> Bool-activeInPhase _ AlwaysActive       = True-activeInPhase _ NeverActive        = False-activeInPhase _ FinalActive        = False-activeInPhase p (ActiveAfter  _ n) = p <= n-activeInPhase p (ActiveBefore _ n) = p >  n+activeInPhase _ AlwaysActive     = True+activeInPhase _ NeverActive      = False+activeInPhase _ FinalActive      = False+activeInPhase p (ActiveAfter  n) = p <= n+activeInPhase p (ActiveBefore n) = p >  n  activeInFinalPhase :: Activation -> Bool activeInFinalPhase AlwaysActive     = True@@ -1562,25 +1605,19 @@ isAlwaysActive AlwaysActive = True isAlwaysActive _            = False -competesWith :: Activation -> Activation -> Bool+-- | @act1 `competesWith` act2@ returns whether @act1@ is active in the phase+-- when @act2@ __becomes__ active.+--+-- This answers the question: might @act1@ fire first?+--+-- NB: this is not the same as computing whether @act1@ and @act2@ are+-- ever active at the same time.+-- -- See Note [Competing activations]-competesWith AlwaysActive      _                = True--competesWith NeverActive       _                = False-competesWith _                 NeverActive      = False--competesWith FinalActive       FinalActive      = True-competesWith FinalActive       _                = False--competesWith (ActiveBefore {})  AlwaysActive      = True-competesWith (ActiveBefore {})  FinalActive       = False-competesWith (ActiveBefore {})  (ActiveBefore {}) = True-competesWith (ActiveBefore _ a) (ActiveAfter _ b) = a < b--competesWith (ActiveAfter {})  AlwaysActive      = False-competesWith (ActiveAfter {})  FinalActive       = True-competesWith (ActiveAfter {})  (ActiveBefore {}) = False-competesWith (ActiveAfter _ a) (ActiveAfter _ b) = a >= b+competesWith :: Activation -> Activation -> Bool+competesWith NeverActive  _           = False+competesWith _            NeverActive = False -- See Wrinkle [Never active rules]+competesWith act1         act2        = isActiveInPhase (beginPhase act2) act1  {- Note [Competing activations] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~@@ -1595,9 +1632,21 @@ active.  For example, a rule might be always active, and an inlining might switch on in phase 2.  We could switch off the rule, but it does no harm.--} +  Wrinkle [Never active rules] +    Rules can be declared as "never active" by users, using the syntax:++      {-# RULE "blah" [~] ... #-}++        (This feature exists solely for compiler plugins, by making it possible+        to define a RULE that is never run by GHC, but is nevertheless parsed,+        typechecked etc, so that it is available to the plugin.)++    We should not warn about competing rules, so make sure that 'competesWith'+    always returns 'False' when its second argument is 'NeverActive'.+-}+ {- ********************************************************************* *                                                                      *                  InlinePragma, InlineSpec, RuleMatchInfo@@ -1855,26 +1904,36 @@ setInlinePragmaRuleMatchInfo prag info = prag { inl_rule = info }  instance Outputable Activation where-   ppr AlwaysActive       = empty-   ppr NeverActive        = brackets (text "~")-   ppr (ActiveBefore _ n) = brackets (char '~' <> int n)-   ppr (ActiveAfter  _ n) = brackets (int n)-   ppr FinalActive        = text "[final]"+   ppr AlwaysActive     = empty+   ppr NeverActive      = brackets (text "~")+   ppr (ActiveBefore n) = brackets (char '~' <> int n)+   ppr (ActiveAfter  n) = brackets (int n)+   ppr FinalActive      = text "[final]" +instance Binary CompilerPhase where+  put_ bh InitialPhase = putByte bh 0+  put_ bh (Phase i)    = do { putByte bh 1; put_ bh i }+  put_ bh FinalPhase   = putByte bh 2++  get bh = do+    h <- getByte bh+    case h of+      0 -> return InitialPhase+      1 -> do { p <- get bh; return (Phase p) }+      _ -> return FinalPhase+ instance Binary Activation where     put_ bh NeverActive =             putByte bh 0-    put_ bh FinalActive =+    put_ bh FinalActive = do             putByte bh 1     put_ bh AlwaysActive =             putByte bh 2-    put_ bh (ActiveBefore src aa) = do+    put_ bh (ActiveBefore aa) = do             putByte bh 3-            put_ bh src             put_ bh aa-    put_ bh (ActiveAfter src ab) = do+    put_ bh (ActiveAfter ab) = do             putByte bh 4-            put_ bh src             put_ bh ab     get bh = do             h <- getByte bh@@ -1882,19 +1941,21 @@               0 -> return NeverActive               1 -> return FinalActive               2 -> return AlwaysActive-              3 -> do src <- get bh-                      aa <- get bh-                      return (ActiveBefore src aa)-              _ -> do src <- get bh-                      ab <- get bh-                      return (ActiveAfter src ab)-+              3 -> do aa <- get bh+                      return (ActiveBefore aa)+              _ -> do ab <- get bh+                      return (ActiveAfter ab)+instance NFData CompilerPhase where+  rnf = \case+    InitialPhase -> ()+    FinalPhase -> ()+    Phase i -> rnf i instance NFData Activation where   rnf = \case     AlwaysActive -> ()     NeverActive -> ()-    ActiveBefore src aa -> rnf src `seq` rnf aa-    ActiveAfter src ab -> rnf src `seq` rnf ab+    ActiveBefore aa -> rnf aa+    ActiveAfter ab -> rnf ab     FinalActive -> ()  instance Outputable RuleMatchInfo where
GHC/Types/Demand.hs view
@@ -2,6 +2,7 @@ {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE BinaryLiterals #-} {-# LANGUAGE PatternSynonyms #-}+{-# LANGUAGE LambdaCase #-}  {- (c) The University of Glasgow 2006@@ -25,6 +26,8 @@     lubCard, lubDmd, lubSubDmd,     -- *** Greatest lower bound     glbCard,+    -- *** Maximum (glb on strictness, lub on usage)+    maxCard, maxDmd,     -- *** Plus     plusCard, plusDmd, plusSubDmd,     -- *** Multiply@@ -51,13 +54,13 @@      -- * Demand environments     DmdEnv(..), addVarDmdEnv, mkTermDmdEnv, nopDmdEnv, plusDmdEnv, plusDmdEnvs,-    multDmdEnv, reuseEnv,+    lubDmdEnv, multDmdEnv, reuseEnv,      -- * Demand types     DmdType(..), dmdTypeDepth,     -- ** Algebra     nopDmdType, botDmdType,-    lubDmdType, plusDmdType, multDmdType, discardArgDmds,+    lubDmdType, maxDmdType, plusDmdType, multDmdType, discardArgDmds,     -- ** Other operations     peelFV, findIdDemand, addDemand, splitDmdTy, deferAfterPreciseException, @@ -866,6 +869,92 @@ -- Otherwise (Call `lub` Prod) return Top lubSubDmd _            _            = topSubDmd +{- Note [Combining demands for stable unfoldings]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+When a function has a stable unfolding, the optimised RHS and the unfolding+may have different demand signatures for the same arguments. This can happen+because:++  * The optimised RHS may have had transformations applied that reveal+    strictness (e.g., inlining exposes a case on an argument).+    Example:+       RHS: x+       Unfolding: head [x]+    It's clear that the RHS is strict in `x`, but the demand analyser won't+    spot that when it analyses the unfolding.++  * The optimised RHS may have had transformations applied that drop usage+    (e.g., a rewrite rule fires that doesn't use an argument, or a seq on+    a dictionary is dropped because dictionaries are known to terminate;+    see Note [NON-BOTTOM-DICTS invariant]).+    Example:+       RHS: a+       Unfolding: fst g+    where `g` is in scope as `g = (a,b)`.++See Note [Absence analysis for stable unfoldings and RULES] in+GHC.Core.Opt.DmdAnal for the broader context.++When we inline the stable unfolding at a call site, we get the unfolding's+behaviour, not the RHS's. So we must be conservative and combine the demands:++  * For strictness (lower bounds): we can take the MAXIMUM (glb).+    If the RHS reveals that an argument is strict, that strictness was+    always there semantically - the analysis just couldn't see it in the+    unfolding. Sound optimisations never make lazy code strict.++  * For usage (upper bounds): we must take the MAXIMUM (lub).+    If the unfolding uses an argument but the RHS doesn't, we must not+    mark it absent, or we'll replace it with rubbish that the unfolding+    will then try to use, causing a segfault. See #26416.++So for cardinality bounds [l1..u1] from RHS and [l2..u2] from unfolding,+we compute [max(l1,l2)..max(u1,u2)].+-}++-- | Takes the maximum of both the lower and upper bound of two 'Card's.+-- Semantically, this is glb on lower (strictness) and lub on upper (usage).+-- See Note [Combining demands for stable unfoldings].+maxCard :: Card -> Card -> Card+-- Given Note [Bit vector representation for Card]:+--   * bit 0 (strictness): take AND (glb) - 0 means strict, so 0 wins+--   * bits 1,2 (usage): take OR (lub) - if either uses, result uses+maxCard (Card a) (Card b) = Card ((a .&. b .&. 0b001) .|. ((a .|. b) .&. 0b110))++-- | Takes the maximum of both the lower and upper bounds of two 'Demand's.+-- Semantically, glb on lower (strictness) and lub on upper (usage).+-- See Note [Combining demands for stable unfoldings].+maxDmd :: Demand -> Demand -> Demand+maxDmd BotDmd      dmd2        = dmd2+maxDmd dmd1        BotDmd      = dmd1+maxDmd AbsDmd      dmd2        = dmd2+maxDmd dmd1        AbsDmd      = dmd1+maxDmd (n1 :* sd1) (n2 :* sd2) =+  maxCard n1 n2 :* maxSubDmd sd1 sd2++maxSubDmd :: SubDemand -> SubDemand -> SubDemand+-- Shortcuts for neutral and absorbing elements.+maxSubDmd (Poly Unboxed C_00)  sd                   = sd+maxSubDmd sd                   (Poly Unboxed C_00)  = sd+maxSubDmd sd@(Poly Boxed C_1N) _                    = sd+maxSubDmd _                    sd@(Poly Boxed C_1N) = sd+-- Prod+maxSubDmd (Prod b1 ds1) (Poly b2 n2)+  | let !d = polyFieldDmd b2 n2+  = mkProd (lubBoxity b1 b2) (strictMap (maxDmd d) ds1)+maxSubDmd (Prod b1 ds1) (Prod b2 ds2)+  | equalLength ds1 ds2+  = mkProd (lubBoxity b1 b2) (strictZipWith maxDmd ds1 ds2)+-- Handle Call+maxSubDmd (Call n1 sd1) (viewCall -> Just (n2, sd2)) =+  mkCall (maxCard n1 n2) (maxSubDmd sd1 sd2)+-- Handle Poly+maxSubDmd (Poly b1 n1) (Poly b2 n2) = Poly (lubBoxity b1 b2) (maxCard n1 n2)+-- Other Poly case by commutativity+maxSubDmd sd1@Poly{}   sd2          = maxSubDmd sd2 sd1+-- Otherwise (Call `max` Prod) return Top+maxSubDmd _            _            = topSubDmd+ -- | Denotes '+' on 'Demand'. plusDmd :: Demand -> Demand -> Demand plusDmd AbsDmd      dmd2        = dmd2@@ -1766,12 +1855,14 @@ exnDmdEnv :: DmdEnv exnDmdEnv = mkEmptyDmdEnv exnDiv +combineDmdEnv :: (Demand -> Demand -> Demand) -> DmdEnv -> DmdEnv -> DmdEnv+combineDmdEnv f (DE fv1 d1) (DE fv2 d2)+  -- See Note [Demand env Equality]+  = DE (plusVarEnv_CD f fv1 (defaultFvDmd d1) fv2 (defaultFvDmd d2))+       (lubDivergence d1 d2)+ lubDmdEnv :: DmdEnv -> DmdEnv -> DmdEnv-lubDmdEnv (DE fv1 d1) (DE fv2 d2) = DE lub_fv lub_div-  where-    -- See Note [Demand env Equality]-    lub_fv  = plusVarEnv_CD lubDmd fv1 (defaultFvDmd d1) fv2 (defaultFvDmd d2)-    lub_div = lubDivergence d1 d2+lubDmdEnv = combineDmdEnv lubDmd  addVarDmdEnv :: DmdEnv -> Id -> Demand -> DmdEnv addVarDmdEnv env@(DE fvs div) id dmd@@ -1825,17 +1916,32 @@     = ds1 == ds2 -- cheap checks first       && env1 == env2 +-- | The smaller 'DmdType' is eta expanded using its 'defaultArgDmd'.+-- See Note [Default demand on free variables and arguments].+zipDmdType :: (Demand -> Demand -> Demand) -> DmdType -> DmdType -> DmdType+zipDmdType f (DmdType fv1 ds1) (DmdType fv2 ds2)+  = DmdType (combineDmdEnv f fv1 fv2) (go ds1 ds2)+  where+    def1, def2 :: Demand  -- Default argument demands for eta expansion+    def1 = defaultArgDmd (de_div fv1)+    def2 = defaultArgDmd (de_div fv2)++    -- If `ds1` is shorter than `ds2`, extend `ds1` with the appropriate+    -- default demand `def1`; and similarly if `ds2` is shorter+    go (d1:ds1') (d2:ds2') = f d1 d2 : go ds1' ds2'+    go []        ds2'      = map (def1 `f`) ds2'+    go ds1'      []        = map (`f` def2) ds1'+ -- | Compute the least upper bound of two 'DmdType's elicited /by the same -- incoming demand/! lubDmdType :: DmdType -> DmdType -> DmdType-lubDmdType d1 d2 = DmdType lub_fv lub_ds-  where-    n = max (dmdTypeDepth d1) (dmdTypeDepth d2)-    (DmdType fv1 ds1) = etaExpandDmdType n d1-    (DmdType fv2 ds2) = etaExpandDmdType n d2-    lub_ds  = zipWithEqual lubDmd ds1 ds2-    lub_fv = lubDmdEnv fv1 fv2+lubDmdType = zipDmdType lubDmd +-- | Combine two 'DmdType's for stable unfolding analysis.+-- See Note [Combining demands for stable unfoldings].+maxDmdType :: DmdType -> DmdType -> DmdType+maxDmdType = zipDmdType maxDmd+ discardArgDmds :: DmdType -> DmdEnv discardArgDmds (DmdType fv _) = fv @@ -2727,7 +2833,10 @@     = ppr div <> if null fv_elts then empty                  else braces (fsep (map pp_elt fv_elts))     where-      pp_elt (uniq, dmd) = ppr uniq <> text "->" <> ppr dmd+      pp_elt (uniq, dmd) =+        sdocOption sdocSuppressUniques $ \case+          True  -> ppr dmd+          False -> ppr uniq <> text "->" <> ppr dmd       fv_elts = nonDetUFMToList fvs         -- It's OK to use nonDetUFMToList here because we only do it for         -- pretty printing
GHC/Types/Error.hs view
@@ -73,6 +73,9 @@    , mkLocMessage    , mkLocMessageWarningGroups    , getCaretDiagnostic++   , jsonDiagnostic+    -- * Queries    , isIntrinsicErrorMessage    , isExtrinsicErrorMessage@@ -109,7 +112,7 @@  import GHC.Version (cProjectVersion) import Data.Bifunctor-import Data.Foldable    ( fold, toList )+import Data.Foldable import Data.List.NonEmpty ( NonEmpty (..) ) import qualified Data.List.NonEmpty as NE import Data.List ( intercalate )@@ -171,9 +174,6 @@                pprDiagnostic (errMsgDiagnostic envelope)              ] -instance (Diagnostic e) => ToJson (Messages e) where-  json msgs =  JSArray . toList $ json <$> getMessages msgs- {- Note [Discarding Messages] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -573,7 +573,7 @@ {- Note [Diagnostic Message JSON Schema] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The below instance of ToJson must conform to the JSON schema-specified in docs/users_guide/diagnostics-as-json-schema-1_1.json.+specified in docs/users_guide/diagnostics-as-json-schema-1_2.json. When the schema is altered, please bump the version. If the content is altered in a backwards compatible way, update the minor version (e.g. 1.3 ~> 1.4).@@ -586,15 +586,17 @@ -}  schemaVersion :: String-schemaVersion = "1.1"+schemaVersion = "1.2"+ -- See Note [Diagnostic Message JSON Schema] before editing!-instance Diagnostic e => ToJson (MsgEnvelope e) where-  json m = JSObject $ [+jsonDiagnostic :: forall e. Diagnostic e => String -> MsgEnvelope e -> JsonDoc+jsonDiagnostic rendered m = JSObject $ [     ("version", JSString schemaVersion),     ("ghcVersion", JSString $ "ghc-" ++ cProjectVersion),     ("span", json $ errMsgSpan m),     ("severity", json $ errMsgSeverity m),     ("code", maybe JSNull json (diagnosticCode diag)),+    ("rendered", JSString rendered),     ("message", JSArray $ map renderToJSString diagMsg),     ("hints", JSArray $ map (renderToJSString . ppr) (diagnosticHints diag) ) ]     ++ [ ("reason", reasonJson)
GHC/Types/Error/Codes.hs view
@@ -405,6 +405,7 @@   GhcDiagnosticCode "DriverModuleGraphCycle"                        = 92213   GhcDiagnosticCode "DriverInstantiationNodeInDependencyGeneration" = 74284   GhcDiagnosticCode "DriverNoConfiguredLLVMToolchain"               = 66599+  GhcDiagnosticCode "DriverSemaphoreOpenFailure"                    = 19877    -- Constraint solver diagnostic codes   GhcDiagnosticCode "BadTelescope"                                  = 97739@@ -699,6 +700,7 @@   GhcDiagnosticCode "TcRnIllegalTypeExpr"                           = 35499   GhcDiagnosticCode "TcRnUnexpectedTypeSyntaxInTerms"               = 31244   GhcDiagnosticCode "TcRnTypeApplicationsDisabled"                  = 23482+  GhcDiagnosticCode "TcRnStaticFormWarning"                         = 82529    -- TcRnIllegalInvisibleTypePattern   GhcDiagnosticCode "InvisPatWithoutFlag"                           = 78249
GHC/Types/ForeignStubs.hs view
@@ -60,10 +60,84 @@ -- | @finalizerCStub fn_nm decls body@ is a 'CStub' containing C finalizer -- function (e.g. an entry of the @.fini_array@ section) named -- @fn_nm@ with the given body and the given set of declarations.+--+-- See Note [Finalizers via __cxa_atexit] finalizerCStub :: Platform -> CLabel -> SDoc -> SDoc -> CStub-finalizerCStub platform clbl declarations body =-    functionCStub platform clbl declarations body+finalizerCStub platform clbl declarations body+  | ArchWasm32 <- platformArch platform+  = -- See Note [Finalizers via __cxa_atexit]+    cxaAtexitFinalizerCStub platform clbl declarations body+finalizerCStub platform clbl declarations body+  | OSDarwin <- platformOS platform+  = -- See Note [Finalizers via __cxa_atexit]+    cxaAtexitFinalizerCStub platform clbl declarations body+finalizerCStub platform clbl declarations body+  = functionCStub platform clbl declarations body     `mappend` CStub empty [] [clbl]++-- | Generate a @__cxa_atexit@-based finalizer.+-- See Note [Finalizers via __cxa_atexit]+cxaAtexitFinalizerCStub :: Platform -> CLabel -> SDoc -> SDoc -> CStub+cxaAtexitFinalizerCStub platform clbl declarations body =+    let clbl_pretty = pprCLabel platform clbl+        fini_name    = hcat [clbl_pretty, text "$fini"]+        wrapper_name = hcat [clbl_pretty, text "$fini_atexit"]+        c_code = vcat+          [ declarations+          , text "int __cxa_atexit(void (*)(void *), void *, void *);"+          , hcat [text "static void ", fini_name, text "(void)"]+          , braces body+          , hcat [text "static void ", wrapper_name, text "(void *arg __attribute__((unused)))"]+          , braces (hcat [fini_name, text "();"])+          , hsep [text "void", clbl_pretty, text "(void)"]+          , braces (hcat [text "__cxa_atexit(", wrapper_name, text ", 0, 0);"])+          ]+    in CStub c_code [clbl] []++{-+Note [Finalizers via __cxa_atexit]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+On some platforms, placing a function pointer in the .fini_array /+__mod_term_func section is not sufficient to have it called on exit.+On these platforms we instead lower finalizers as initializers that register+the actual finalizer function via __cxa_atexit.++Affected platforms:++  Wasm32: does not support .fini_array sections.++  Darwin: modern macOS dyld no longer processes __DATA,__mod_term_func entries.+  Clang now lowers __attribute__((destructor)) as an initializer that calls+  __cxa_atexit, placing the initializer in __DATA,__mod_init_func (which the+  linker converts to __TEXT,__init_offsets). GHC must follow the same pattern.++For a finalizer with label `clbl` and body `body`, on these platforms we+generate:++    static void clbl$fini(void) {+        <body>+    }+    static void clbl$fini_atexit(void *arg) {+        clbl$fini();+    }+    void clbl(void) {+        __cxa_atexit(clbl$fini_atexit, 0, 0);+    }++The function `clbl` is placed in the initializers list (getInitializers)+instead of the finalizers list (getFinalizers). During code output,+emitInitializerDecls places it in .init_array / __mod_init_func, so the+registration runs at startup.++The actual finalizer body is in the static helper `clbl$fini`. A separate+wrapper `clbl$fini_atexit` with the void(*)(void*) signature expected by+__cxa_atexit is needed because some platforms (e.g. wasm32) enforce exact+function signature matching at call sites — a simple cast would trap at+runtime.++This matches what clang does when lowering __attribute__((destructor)) on+these platforms.+-}  newtype CHeader = CHeader { getCHeader :: SDoc } 
GHC/Types/Hint.hs view
@@ -12,6 +12,7 @@   , StarIsType(..)   , UntickedPromotedThing(..)   , AssumedDerivingStrategy(..)+  , SemaphoreUpgradeTarget(..)   , SigLike(..)   , pprUntickedConstructor, isBareSymbol   , suggestExtension@@ -513,6 +514,29 @@    {-| Suggest using the `data` keyword -}   | SuggestDataKeyword++  {-| Suggest upgrading either the @-jsem@ jobserver or GHC itself to+      support the given semaphore protocol version.++      Triggered by 'GHC.Driver.Errors.Types.DriverSemaphoreOpenFailure'+      carrying a 'System.Semaphore.SemaphoreIncompatibleVersion'.+  -}+  | SuggestUpgradeForSemaphoreVersionMismatch !SemaphoreUpgradeTarget !Int+    -- ^ The 'Int' is the required protocol version.++-- | What the user should upgrade to resolve an @-jsem@ semaphore+--   protocol version mismatch.+data SemaphoreUpgradeTarget+  = UpgradeCabalInstall+    -- ^ Jobserver is @cabal-install@ (we are building a Cabal package)+    --   and speaks an older protocol than GHC.+  | UpgradeJobserver+    -- ^ Jobserver (not @cabal-install@) speaks an older protocol than+    --   GHC.+  | UpgradeGHC+    -- ^ Jobserver speaks a newer protocol than GHC.+  deriving (Eq, Show)+  -- | The deriving strategy that was assumed when not explicitly listed in the --   source. This is used solely by the missing-deriving-strategies warning.
GHC/Types/Hint/Ppr.hs view
@@ -293,6 +293,20 @@       -> text "Split the SPECIALISE pragma into multiple pragmas, one for each type signature"     SuggestDataKeyword       -> text "Use the" <+> quotes (text "data") <+> "keyword instead."+    SuggestUpgradeForSemaphoreVersionMismatch target required+      -> case target of+           UpgradeCabalInstall ->+                 text "The cabal-install jobserver uses an older semaphore protocol."+              $$ (text "Upgrade cabal-install to a version that supports semaphore protocol v"+                  <> int required <> text " to resolve this.")+           UpgradeJobserver ->+                 text "The jobserver uses an older semaphore protocol."+              $$ (text "Upgrade it to a version that supports semaphore protocol v"+                  <> int required <> text " to resolve this.")+           UpgradeGHC ->+                 text "The jobserver uses a newer semaphore protocol than this GHC."+              $$ (text "Upgrade GHC to a version that supports semaphore protocol v"+                  <> int required <> text " to resolve this.")  perhapsAsPat :: SDoc perhapsAsPat = text "Perhaps you meant an as-pattern, which must not be surrounded by whitespace"
GHC/Types/Id/Info.hs view
@@ -20,6 +20,7 @@ module GHC.Types.Id.Info (         -- * The IdDetails type         IdDetails(..), pprIdDetails, coVarDetails, isCoVarDetails,+        mkDFunIdDetails,         JoinArity, isJoinIdDetails_maybe,          RecSelParent(..), recSelParentName, recSelFirstConName,@@ -201,9 +202,8 @@   | TickBoxOpId TickBoxOp       -- ^ The 'Id' is for a HPC tick box (both traditional and binary)    | DFunId Bool                 -- ^ A dictionary function.-       -- Bool = True <=> the class has only one method, so may be-       --                  implemented with a newtype, so it might be bad-       --                  to be strict on this dictionary+       -- Bool = True <=> a dictionary of this class cannot be bottom+       -- See Note [NON-BOTTOM-DICTS invariant] in GHC.Core    | CoVarId    -- ^ A coercion variable                -- This only covers /un-lifted/ coercions, of type@@ -387,6 +387,9 @@ isJoinIdDetails_maybe (JoinId join_arity marks) = Just (join_arity, marks) isJoinIdDetails_maybe _                   = Nothing +mkDFunIdDetails :: Class -> IdDetails+mkDFunIdDetails cls = DFunId (isTerminatingTyCon (classTyCon cls))+ instance Outputable IdDetails where     ppr = pprIdDetails @@ -403,7 +406,8 @@    pp (PrimOpId {})           = text "PrimOp"    pp (FCallId _)             = text "ForeignCall"    pp (TickBoxOpId _)         = text "TickBoxOp"-   pp (DFunId nt)             = text "DFunId" <> ppWhen nt (text "(nt)")+   pp (DFunId terminating)    = text "DFunId"+                                <> ppWhen (not terminating) (text "(may-be-bottom)")    pp (RecSelId { sel_naughty = is_naughty })                               = brackets $ text "RecSel" <>                                            ppWhen is_naughty (text "(naughty)")@@ -583,7 +587,12 @@ -- ^ True of a /non-loop-breaker/ Id that has a /stable/ unfolding that is --   (a) always inlined; that is, with an `UnfWhen` guidance, or --   (b) a DFunUnfolding which never needs to be inlined-hasInlineUnfolding info = isInlineUnfolding (unfoldingInfo info)+--+-- Very important that this work with `realUnfoldingInfo` and so returns+-- True even for a loop-breaker that has an INLINE pragma.+-- See (CWW4) in Note [Cast worker/wrapper] in GHC.Core.Opt.Simplify.Iteration+-- for discussion, and #26903 for the dire consequences of getting this wrong.+hasInlineUnfolding info = isInlineUnfolding (realUnfoldingInfo info)  setArityInfo :: IdInfo -> ArityInfo -> IdInfo setArityInfo info ar =
GHC/Types/Id/Make.hs view
@@ -67,7 +67,6 @@ import GHC.Core.DataCon  import GHC.Types.Literal-import GHC.Types.SourceText import GHC.Types.RepType ( countFunRepArgs, typePrimRep ) import GHC.Types.Name.Set import GHC.Types.Name@@ -1845,11 +1844,10 @@ -- See Note [Dict funs and default methods]  mkDictFunId dfun_name tvs theta clas tys-  = mkExportedLocalId (DFunId is_unary)+  = mkExportedLocalId (mkDFunIdDetails clas)                       dfun_name                       dfun_ty   where-    is_unary = isUnaryClass clas     dfun_ty  = TcType.tcMkDFunSigmaTy tvs theta (mkClassPred clas tys)  {-@@ -1926,8 +1924,7 @@                        `setArityInfo`      arity      inline_prag-         = alwaysInlinePragma `setInlinePragmaActivation` ActiveAfter-                 NoSourceText 0+         = alwaysInlinePragma `setInlinePragmaActivation` ActiveAfter 0                   -- Make 'seq' not inline-always, so that simpleOptExpr                   -- (see GHC.Core.Subst.simple_app) won't inline 'seq' on the                   -- LHS of rules.  That way we can have rules for 'seq';
GHC/Types/Literal.hs view
@@ -1014,6 +1014,14 @@     This is sad, though: see #18983. +   INVARIANT 3: we never make a rubbish literal of a terminating type+   (isTerminatingType), such as a class dictionary. GHC relies on a value of+   a terminating type never being bottom, and so may speculatively evaluate+   a dictionary or select a superclass from it. Either would crash on a+   rubbish literal (#24934, #25924).+   See Note [Don't make fillers for constraint types]+   in GHC.Core.Opt.WorkWrap.Utils.+ 3. STG: The type app in `RUBBISH[IntRep] @Int# :: Int#` is erased and we get    the (untyped) 'StgLit' `RUBBISH[IntRep] :: Int#` in STG. 
GHC/Types/Name/Reader.hs view
@@ -45,7 +45,7 @@         isOrig, isOrig_maybe, isExact, isExact_maybe, isSrcRdrName,          -- ** Preserving user-written qualification-        WithUserRdr(..), noUserRdr, unLocWithUserRdr, userRdrName,+        WithUserRdr(..), noUserRdr, unLocWithUserRdr, userRdrName, unwrapUserRdr,          -- * Local mapping of 'RdrName' to 'Name.Name'         LocalRdrEnv, emptyLocalRdrEnv, extendLocalRdrEnv, extendLocalRdrEnvList,@@ -2170,8 +2170,8 @@ instance Outputable ImportSpec where    ppr imp_spec      = text "imported" <+> qual-        <+> text "from" <+> quotes (ppr (importSpecModule imp_spec))         <+> level_ppr+        <+> text "from" <+> quotes (ppr (importSpecModule imp_spec))         <+> pprLoc (importSpecLoc imp_spec)      where        qual | is_qual (is_decl imp_spec) = text "qualified"@@ -2180,7 +2180,7 @@        level = thLevelIndexFromImportLevel (is_level (is_decl imp_spec))        level_ppr         | level == topLevelIndex = empty-        | otherwise = text "at" <+> ppr level+        | otherwise = text "at level" <+> ppr level   pprLoc :: SrcSpan -> SDoc@@ -2220,8 +2220,11 @@ noUserRdr :: Name -> WithUserRdr Name noUserRdr n = WithUserRdr (nameRdrName n) n -userRdrName :: WithUserRdr Name -> RdrName+userRdrName :: WithUserRdr a -> RdrName userRdrName (WithUserRdr rdr _) = rdr++unwrapUserRdr :: WithUserRdr a -> a+unwrapUserRdr (WithUserRdr _ a) = a  rdrQual_maybe :: RdrName -> Maybe ModuleName rdrQual_maybe = \case
GHC/Types/RepType.hs view
@@ -1,3 +1,4 @@+{-# LANGUAGE MultiWayIf #-}  {-# LANGUAGE FlexibleContexts #-} @@ -80,13 +81,21 @@ isNvUnaryRep [_] = True isNvUnaryRep _ = False --- | Gets rid of the stuff that prevents us from understanding the--- runtime representation of a type. Including:---   1. Casts---   2. Newtypes---   3. Foralls---   4. Synonyms--- But not type/data families, because we don't have the envs to hand.+-- | Look through casts, foralls, type synonyms, newtypes and unary classes+-- at the top-level of a type.+--+-- Does /not/ reduce type family applications nor peel off data family instance+-- newtypes.+--+-- Use this function to try to discover the 'TyCon' used to represent values+-- of a type at runtime:+--+--   * the function arrow: the values are functions;+--   * a data type: the values are built from its data constructors;+--   * a primitive type constructor (e.g. @Int#@, @ByteArray#@).+--+-- __Warning__: do __not__ use this function to compute the runtime+-- representation of a type (#26695). That's what 'typePrimRep' is for. unwrapType :: Type -> Type unwrapType ty   | Just (_, unwrapped)@@ -104,12 +113,20 @@       -- cf. Coercion.unwrapNewTypeStepper     stepper rec_nts tc tys+      -- Unwrap newtypes.       | Just (ty', _) <- instNewTyCon_maybe tc tys-      = case checkRecTc rec_nts tc of-          Just rec_nts' -> NS_Step rec_nts' (go ty') ()-          Nothing       -> NS_Abort   -- infinite newtypes+      = step ty'+      -- Look through unary classes.+      | Just (_cls, dc) <- isUnaryClassTyCon_maybe tc+      , [Scaled _ ty'] <- dataConInstArgTys dc tys+      = step ty'       | otherwise       = NS_Done+      where+        step ty' =+          case checkRecTc rec_nts tc of+            Just rec_nts' -> NS_Step rec_nts' (go ty') ()+            Nothing       -> NS_Abort -- fell into a loop (e.g. recursive newtypes)  -- | Count the arity of a function post-unarisation, including zero-width arguments. --@@ -686,19 +703,33 @@  -------------- mightBeFunTy :: Type -> Bool--- Return False only if we are *sure* it's a data type--- Look through newtypes etc as much as possible. Used to--- decide if we need to enter a closure via a slow call.+-- ^ Might this type be a function type, including after looking through+-- newtypes, unary classes, and reducing type family applications? ----- AK: It would be nice to figure out and document the difference--- between this and isFunTy at some point.+-- In particular, returns @True@ for @IO a@: after unwrapping the newtype,+-- we get @State# RealWorld -> (# State# RealWorld, a #)@, which is indeed a+-- function type.+--+-- This function is conservative: it returns @False@ only if the type is+-- **definitely not** a function type. It returns @True@ when it's not sure,+-- e.g. for a type family application.+--+-- This function is generally used when we can perform certain optimisations+-- when we are sure a type is not a function type (i.e. operationally does not+-- take a value argument at runtime).+--+-- This is different from 'isFunTy', which only returns @True@ when the type+-- is a function arrow on-the-nose (without looking through newtypes).+-- In particular, 'isFunTy' returns @False@ for @IO ()@ as well as for all+-- type family applications. mightBeFunTy ty-  -- Currently ghc has no unlifted functions.+  -- GHC (currently) has no unlifted functions, so an unlifted type is+  -- definitely not a function type.   | definitelyUnliftedType ty   = False-  | [BoxedRep _] <- typePrimRep ty-  , Just tc <- tyConAppTyCon_maybe (unwrapType ty)-  , isBoxedDataTyCon tc-  = False+  | Just tc <- tyConAppTyCon_maybe (unwrapType ty)+  -- A proper datatype (such as 'Int' or 'Maybe Bool') is definitely not+  -- a function type. (This does not include newtypes nor type families.)+  = not $ isBoxedDataTyCon tc   | otherwise   = True
GHC/Types/Unique.hs view
@@ -94,8 +94,8 @@ -- for fast ordering and equality tests. You should generate these with -- the functions from the 'UniqSupply' module ----- These are sometimes also referred to as \"keys\" in comments in GHC. newtype Unique = MkUnique Word64+-- These are sometimes also referred to as \"keys\" in comments in GHC.  {-# INLINE uNIQUE_BITS #-} uNIQUE_BITS :: Int
GHC/Types/Unique/DFM.hs view
@@ -95,6 +95,11 @@ -- If the client of the map performs operations on the map in deterministic -- order then `udfmToList` returns them in deterministic order. --+-- The order does not depend on how existing entries were+-- updated. Updating an existing entry keeps it original position in the order+-- This means `alterUDFM` consistent with `addToUDFM` and `adjustUDFM`,+-- so that for example `alterUDFM id k = id` and `alterUDFM (fmap f) k = adjustUDFM f k`+-- -- There is an implementation cost: each element is given a serial number -- as it is added, and `udfmToList` sorts its result by this serial -- number. So you should only use `UniqDFM` if you need the deterministic@@ -114,6 +119,14 @@ -- every value with the insertion time that can later be used to sort the -- values when asked to convert to a list. --+-- Updating an existing key keeps the old tag. This keeps the order stable for+-- maps whose entries are updated many times. The instance environments are+-- the main example: inserting an instance updates the entry of its class in a+-- DNameEnv, and when updates moved keys to the end the order of instances shown+-- by :info depended on the order in which interfaces happened to be loaded+-- (#27532). Now a class keeps its place once its first instance is added, so+-- loading further interfaces cannot change the order.+-- -- An alternative would be to have -- --   data UniqDFM ele = UDFM (M.IntMap ele) [ele]@@ -173,11 +186,13 @@ unitUDFM :: Uniquable key => key -> elt -> UniqDFM key elt unitUDFM k v = UDFM (M.singleton (getKey $ getUnique k) (TaggedVal v 0)) 1 --- The new binding always goes to the right of existing ones+-- A new key goes to the right of existing ones+-- Overwriting an existing key keeps its position in the iteration order addToUDFM :: Uniquable key => UniqDFM key elt -> key -> elt  -> UniqDFM key elt addToUDFM m k v = addToUDFM_Directly m (getUnique k) v --- The new binding always goes to the right of existing ones+-- A new key goes to the right of existing ones+-- Overwriting an existing key keeps its position in the iteration order addToUDFM_Directly :: UniqDFM key elt -> Unique -> elt -> UniqDFM key elt addToUDFM_Directly (UDFM m i) u v   = UDFM (MS.insertWith tf (getKey u) (TaggedVal v i) m) (i + 1)@@ -439,7 +454,8 @@ -- | The expression (alterUDFM f k map) alters value x at k, or absence -- thereof. alterUDFM can be used to insert, delete, or update a value in -- UniqDFM. Use addToUDFM, delFromUDFM or adjustUDFM when possible, they are--- more efficient.+-- more efficient. Updating an existing key keeps its position in the+-- deterministic iteration order. alterUDFM   :: Uniquable key   => (Maybe elt -> Maybe elt)  -- How to adjust@@ -449,10 +465,10 @@ alterUDFM f (UDFM m i) k =   UDFM (M.alter alterf (getKey $ getUnique k) m) (i + 1)   where-  alterf Nothing = inject $ f Nothing-  alterf (Just (TaggedVal v _)) = inject $ f (Just v)-  inject Nothing = Nothing-  inject (Just v) = Just $ TaggedVal v i+  alterf Nothing = inject i $ f Nothing+  alterf (Just (TaggedVal v old_i)) = inject old_i $ f (Just v)+  inject _ Nothing = Nothing+  inject tag (Just v) = Just $ TaggedVal v tag  -- | Map a function over every value in a UniqDFM mapUDFM :: (elt1 -> elt2) -> UniqDFM key elt1 -> UniqDFM key elt2
GHC/Types/Unique/FM.hs view
@@ -41,6 +41,7 @@         listToUFM_C,         listToIdentityUFM,         addToUFM,addToUFM_C,addToUFM_Acc,addToUFM_L,+        strictAddToUFM_C,         addListToUFM,addListToUFM_C,         addToUFM_Directly,         addListToUFM_Directly,@@ -51,7 +52,9 @@         delListFromUFM,         delListFromUFM_Directly,         plusUFM,+        strictPlusUFM,         plusUFM_C,+        strictPlusUFM_C,         plusUFM_CD,         plusUFM_CD2,         mergeUFM,@@ -63,6 +66,7 @@         minusUFM_C,         intersectUFM,         intersectUFM_C,+        strictIntersectUFM_C,         disjointUFM,         equalKeysUFM,         diffUFM,@@ -179,6 +183,16 @@ addToUFM_C f (UFM m) k v =   UFM (M.insertWith (flip f) (getKey $ getUnique k) v m) +strictAddToUFM_C+  :: Uniquable key+  => (elt -> elt -> elt)  -- ^ old -> new -> result+  -> UniqFM key elt       -- ^ old+  -> key -> elt           -- ^ new+  -> UniqFM key elt       -- ^ result+-- Arguments of combining function of MS.insertWith and strictAddToUFM_C are flipped.+strictAddToUFM_C f (UFM m) k v =+  UFM (MS.insertWith (flip f) (getKey $ getUnique k) v m)+ addToUFM_Acc   :: Uniquable key   => (elt -> elts -> elts)  -- Add to existing@@ -251,16 +265,24 @@ delFromUFM_Directly :: UniqFM key elt -> Unique -> UniqFM key elt delFromUFM_Directly (UFM m) u = UFM (M.delete (getKey u) m) --- Bindings in right argument shadow those in the left+-- | Bindings in right argument shadow those in the left.+--+-- Unlike containers this union is right-biased for historic reasons. plusUFM :: UniqFM key elt -> UniqFM key elt -> UniqFM key elt--- M.union is left-biased, plusUFM should be right-biased. plusUFM (UFM x) (UFM y) = UFM (M.union y x)      -- Note (M.union y x), with arguments flipped      -- M.union is left-biased, plusUFM should be right-biased. +-- | Right biased+strictPlusUFM :: UniqFM key elt -> UniqFM key elt -> UniqFM key elt+strictPlusUFM (UFM x) (UFM y) = UFM (MS.union y x)+ plusUFM_C :: (elt -> elt -> elt) -> UniqFM key elt -> UniqFM key elt -> UniqFM key elt plusUFM_C f (UFM x) (UFM y) = UFM (M.unionWith f x y) +strictPlusUFM_C :: (elt -> elt -> elt) -> UniqFM key elt -> UniqFM key elt -> UniqFM key elt+strictPlusUFM_C f (UFM x) (UFM y) = UFM (MS.unionWith f x y)+ -- | `plusUFM_CD f m1 d1 m2 d2` merges the maps using `f` as the -- combinding function and `d1` resp. `d2` as the default value if -- there is no entry in `m1` reps. `m2`. The domain is the union of@@ -370,6 +392,13 @@   -> UniqFM key elt2   -> UniqFM key elt3 intersectUFM_C f (UFM x) (UFM y) = UFM (M.intersectionWith f x y)++strictIntersectUFM_C+  :: (elt1 -> elt2 -> elt3)+  -> UniqFM key elt1+  -> UniqFM key elt2+  -> UniqFM key elt3+strictIntersectUFM_C f (UFM x) (UFM y) = UFM (MS.intersectionWith f x y)  disjointUFM :: UniqFM key elt1 -> UniqFM key elt2 -> Bool disjointUFM (UFM x) (UFM y) = M.disjoint x y
GHC/Types/Unique/Set.hs view
@@ -21,12 +21,14 @@         emptyUniqSet,         unitUniqSet,         mkUniqSet,-        addOneToUniqSet, addListToUniqSet,+        addOneToUniqSet, addListToUniqSet, strictAddOneToUniqSet_C,         delOneFromUniqSet, delOneFromUniqSet_Directly, delListFromUniqSet,         delListFromUniqSet_Directly,         unionUniqSets, unionManyUniqSets,-        minusUniqSet, uniqSetMinusUFM, uniqSetMinusUDFM,-        intersectUniqSets,+        strictUnionUniqSets_C, strictUnionManyUniqSets_C,+        minusUniqSet, minusUniqSet_C,+        uniqSetMinusUFM, uniqSetMinusUDFM,+        intersectUniqSets, strictIntersectUniqSets_C,         disjointUniqSets,         restrictUniqSetToUFM,         uniqSetAny, uniqSetAll,@@ -110,6 +112,10 @@ addListToUniqSet = foldl' addOneToUniqSet {-# INLINEABLE addListToUniqSet #-} +strictAddOneToUniqSet_C :: Uniquable a => (a -> a -> a) -> UniqSet a -> a -> UniqSet a+strictAddOneToUniqSet_C f (UniqSet set) x =+  UniqSet (strictAddToUFM_C f set x x)+ delOneFromUniqSet :: Uniquable a => UniqSet a -> a -> UniqSet a delOneFromUniqSet (UniqSet s) a = UniqSet (delFromUFM s a) @@ -128,14 +134,28 @@ unionUniqSets :: UniqSet a -> UniqSet a -> UniqSet a unionUniqSets (UniqSet s) (UniqSet t) = UniqSet (plusUFM s t) +strictUnionUniqSets_C :: (a -> a -> a) -> UniqSet a -> UniqSet a -> UniqSet a+strictUnionUniqSets_C f (UniqSet s) (UniqSet t) =+  UniqSet (strictPlusUFM_C f s t)+ unionManyUniqSets :: [UniqSet a] -> UniqSet a unionManyUniqSets = foldl' (flip unionUniqSets) emptyUniqSet +strictUnionManyUniqSets_C :: (a -> a -> a) -> [UniqSet a] -> UniqSet a+strictUnionManyUniqSets_C f = foldl' (flip (strictUnionUniqSets_C f)) emptyUniqSet+ minusUniqSet  :: UniqSet a -> UniqSet a -> UniqSet a minusUniqSet (UniqSet s) (UniqSet t) = UniqSet (minusUFM s t) +minusUniqSet_C :: (a -> a -> Maybe a) -> UniqSet a -> UniqSet a -> UniqSet a+minusUniqSet_C f (UniqSet s) (UniqSet t) = UniqSet (minusUFM_C f s t)+ intersectUniqSets :: UniqSet a -> UniqSet a -> UniqSet a intersectUniqSets (UniqSet s) (UniqSet t) = UniqSet (intersectUFM s t)++strictIntersectUniqSets_C :: (a -> a -> a) -> UniqSet a -> UniqSet a -> UniqSet a+strictIntersectUniqSets_C f (UniqSet s) (UniqSet t) =+  UniqSet (strictIntersectUFM_C f s t)  disjointUniqSets :: UniqSet a -> UniqSet a -> Bool disjointUniqSets (UniqSet s) (UniqSet t) = disjointUFM s t
GHC/Types/Var/Env.hs view
@@ -12,7 +12,8 @@         elemVarEnv, disjointVarEnv, anyVarEnv,         extendVarEnv, extendVarEnv_C, extendVarEnv_Acc,         extendVarEnvList,-        plusVarEnv, plusVarEnv_C, plusVarEnv_CD, plusMaybeVarEnv_C,+        strictPlusVarEnv, plusVarEnv, plusVarEnv_C, strictPlusVarEnv_C,+        plusVarEnv_CD, plusMaybeVarEnv_C,         plusVarEnvList, alterVarEnv,         delVarEnvList, delVarEnv,         minusVarEnv,@@ -511,6 +512,7 @@ extendVarEnv_C    :: (a->a->a) -> VarEnv a -> Var -> a -> VarEnv a extendVarEnv_Acc  :: (a->b->b) -> (a->b) -> VarEnv b -> Var -> a -> VarEnv b plusVarEnv        :: VarEnv a -> VarEnv a -> VarEnv a+strictPlusVarEnv  :: VarEnv a -> VarEnv a -> VarEnv a plusVarEnvList    :: [VarEnv a] -> VarEnv a extendVarEnvList  :: VarEnv a -> [(Var, a)] -> VarEnv a varEnvDomain      :: VarEnv elt -> UnVarSet@@ -522,6 +524,7 @@ delVarEnv         :: VarEnv a -> Var -> VarEnv a minusVarEnv       :: VarEnv a -> VarEnv b -> VarEnv a plusVarEnv_C      :: (a -> a -> a) -> VarEnv a -> VarEnv a -> VarEnv a+strictPlusVarEnv_C :: (a -> a -> a) -> VarEnv a -> VarEnv a -> VarEnv a plusVarEnv_CD     :: (a -> a -> a) -> VarEnv a -> a -> VarEnv a -> a -> VarEnv a plusMaybeVarEnv_C :: (a -> a -> Maybe a) -> VarEnv a -> VarEnv a -> VarEnv a mapVarEnv         :: (a -> b) -> VarEnv a -> VarEnv b@@ -548,6 +551,7 @@ extendVarEnv_Acc = addToUFM_Acc extendVarEnvList = addListToUFM plusVarEnv_C     = plusUFM_C+strictPlusVarEnv_C = strictPlusUFM_C plusVarEnv_CD    = plusUFM_CD plusMaybeVarEnv_C = plusMaybeUFM_C delVarEnvList    = delListFromUFM@@ -556,6 +560,7 @@ delVarEnv        = delFromUFM minusVarEnv      = minusUFM plusVarEnv       = plusUFM+strictPlusVarEnv = strictPlusUFM plusVarEnvList   = plusUFMList -- lookupVarEnv is very hot (in part due to being called by substTyVar), -- if it's not inlined than the mere allocation of the Just constructor causes
GHC/Unit.hs view
@@ -228,8 +228,8 @@ A 'VirtUnit' may be indefinite or definite, it depends on whether some holes remain in the instantiated unit OR in the instantiating units (recursively). Having a fully instantiated (i.e. definite) virtual unit can lead to some issues-if there is a matching compiled unit in the preload closure.  See Note [VirtUnit-to RealUnit improvement]+if there is a matching compiled unit in the preload closure.+See Note [VirtUnit to RealUnit improvement]  Unit database and indefinite units ----------------------------------@@ -316,7 +316,6 @@       (i.e. GHC doesn't correctly call `pprWithUnitState` before pretty-printing a       UnitId), that's what will be shown to the user so it's no big deal. - Note [VirtUnit to RealUnit improvement] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -334,6 +333,8 @@ As we want them to match we just replace the virtual unit with the installed one: for some reason this is called "improvement". +HISTORICAL:+ There is one last niggle: improvement based on the unit database means that we might end up developing on a unit that is not transitively depended upon by the units the user specified directly via command line@@ -341,6 +342,12 @@ instantiations are out of date.  The solution is to only improve a unit id if the new unit id is part of the 'preloadClosure'; i.e., the closure of all the units which were explicitly specified.++NOTE:++The 'preloadClosure' was completely unused, thus we removed it without+changing any of the tests. It doesn't seem to be necessary any more.+It is unclear at which exact point this became redundant.  Note [Representation of module/name variables] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
GHC/Unit/Env.hs view
@@ -43,6 +43,8 @@     ( UnitEnv (..)     , initUnitEnv     , ueEPS -- Not really needed, get directly type families and rule base!+    , ueEUD+    , ueUI     , updateHug     -- * Unit Env helper functions     , ue_currentHomeUnitEnv@@ -83,7 +85,6 @@      -- ** Queries on the current active home unit     , ue_homeUnitState-    , ue_unit_dbs     , ue_homeUnit     , ue_unitFlags @@ -113,6 +114,8 @@ import qualified Data.Set as Set  import GHC.Unit.External+import GHC.Unit.External.Database+import GHC.Unit.External.Index import GHC.Unit.State import GHC.Unit.Home import GHC.Unit.Types@@ -177,14 +180,31 @@      , ue_namever   :: !GhcNameVersion         -- ^ GHC name/version (used for dynamic library suffix)++    , ue_uic :: {-# UNPACK #-} !UnitIndexCache+        -- ^ Global index of already processed external units.+        -- Shares state over all 'UnitState's in the 'HomeUnitGraph'.+        --+        -- Allows sharing of 'UnitInfo's, ensuring each individual 'UnitInfo'+        -- is retained a constant number of times.+        --+        -- See Note [Sharing 'UnitInfo's across the 'UnitEnv'] for details.     }  ueEPS :: UnitEnv -> IO ExternalPackageState ueEPS = eucEPS . ue_eps +ueEUD :: UnitEnv -> IO (ExternalUnitDatabases UnitId)+ueEUD = readExternalUnitDatabases . ue_uic++ueUI :: UnitEnv -> IO UnitIndex+ueUI = readUnitIndex . ue_uic++ initUnitEnv :: UnitId -> HomeUnitGraph -> GhcNameVersion -> Platform -> IO UnitEnv initUnitEnv cur_unit hug namever platform = do   eps <- initExternalUnitCache+  uic <- initUnitIndexCache   return $ UnitEnv     { ue_eps             = eps     , ue_home_unit_graph = hug@@ -192,6 +212,7 @@     , ue_current_unit    = cur_unit     , ue_platform        = platform     , ue_namever         = namever+    , ue_uic      = uic     }  updateHug :: (HomeUnitGraph -> HomeUnitGraph) -> UnitEnv -> UnitEnv@@ -260,9 +281,6 @@  ue_homeUnitState :: HasDebugCallStack => UnitEnv -> UnitState ue_homeUnitState = HUG.homeUnitEnv_units . ue_currentHomeUnitEnv--ue_unit_dbs :: UnitEnv ->  Maybe [UnitDatabase UnitId]-ue_unit_dbs = HUG.homeUnitEnv_unit_dbs . ue_currentHomeUnitEnv  -- ------------------------------------------------------- -- Query and modify Home Package Table in HomeUnitEnv
+ GHC/Unit/External/Database.hs view
@@ -0,0 +1,366 @@+module GHC.Unit.External.Database (+  -- * 'ExternalUnitDatabases'+  ExternalUnitDatabases,+  emptyExternalUnitDatabases,+  insertExternalUnitDatabases,+  deleteExternalUnitDatabases,+  lookupExternalUnitDatabases,+  -- * 'UnitDatabase' and how to merge them.+  UnitDatabase (..),+  mergeDatabases,+  UnitPrecedenceMap,+  sortByPreference,+  compareByPreference,+  -- * Reading packages from disk.+  UnitDbConfig (..),+  readUnitDatabase,+  getUnitDbRefs,+  resolveUnitDatabase,+) where++import GHC.Prelude++import GHC.Data.Maybe+import GHC.Data.OsPath (OsPath)+import GHC.Data.OsPath qualified as OsPath+import GHC.Data.ShortText qualified as ST+import GHC.Driver.DynFlags+import GHC.Platform.ArchOS+import GHC.Types.Unique.Map+import GHC.Unit.Database+import GHC.Unit.Info+import GHC.Unit.Types+import GHC.Utils.Error+import GHC.Utils.Exception+import GHC.Utils.Logger+import GHC.Utils.Misc+import GHC.Utils.Outputable as Outputable+import GHC.Utils.Panic++import Control.Monad+import Data.Char+import Data.List (sortBy)+import Data.Map.Strict (Map)+import Data.Map.Strict qualified as Map+import Data.Ord+import Data.Set (Set)+import Data.Set qualified as Set+import System.Directory+import System.Environment (getEnv)+import System.FilePath as FilePath++-- ----------------------------------------------------------------------------+-- ExternalUnitDatabases+-- ----------------------------------------------------------------------------++-- | A normalised 'OsPath' that we use as the key to cache 'UnitDatabase's.+--+-- Removes trailing path separators and unit database paths starting with @./@.+newtype NormalisedUnitDbLoc = NormalisedUnitDbLoc OsPath+  deriving (Eq, Ord)++-- | Caches unit databases in-memory.+data ExternalUnitDatabases unit = ExternalUnitDatabases+  { eud_cachedDatabases :: !(Map NormalisedUnitDbLoc (UnitDatabase unit))+  -- ^ The 'Map' is keyed by a normalised 'OsPath', ensuring that 'lookupExternalUnitDatabases'+  -- will never get confused by a stray @./@ or trailing @/@.+  }++emptyExternalUnitDatabases :: ExternalUnitDatabases unit+emptyExternalUnitDatabases =+  ExternalUnitDatabases+    { eud_cachedDatabases = Map.empty+    }++insertExternalUnitDatabases :: UnitDatabase unit -> ExternalUnitDatabases unit -> ExternalUnitDatabases unit+insertExternalUnitDatabases unit_db eud =+  ExternalUnitDatabases+    { eud_cachedDatabases =+        Map.insert (normalisedUnitDatabaseKey unit_db) unit_db (eud_cachedDatabases eud)+    }++deleteExternalUnitDatabases :: OsPath -> ExternalUnitDatabases unit -> ExternalUnitDatabases unit+deleteExternalUnitDatabases unit_db_path eud =+  ExternalUnitDatabases+    { eud_cachedDatabases =+        Map.delete (normalisedUnitDatabaseKeyOsPath unit_db_path) (eud_cachedDatabases eud)+    }++lookupExternalUnitDatabases :: OsPath -> ExternalUnitDatabases unit -> Maybe (UnitDatabase unit)+lookupExternalUnitDatabases key eud =+  Map.lookup (normalisedUnitDatabaseKeyOsPath key) (eud_cachedDatabases eud)++-- ----------------------------------------------------------------------------+-- UnitDatabase+-- ----------------------------------------------------------------------------++-- | Unit database entry.+data UnitDatabase unit = UnitDatabase+  { unitDatabasePath :: OsPath+  -- ^ On-disk location of the unit database.+  --+  , unitDatabaseUnits :: [GenUnitInfo unit]+  -- ^ Units read from the database located at 'unitDatabasePath'.+  --+  -- These units have the @$pkgroot@ variable already resolved.+  }++instance (Outputable u) => Outputable (UnitDatabase u) where+  ppr (UnitDatabase fp _u) = text "DB:" <+> ppr fp++normalisedUnitDatabaseKey :: UnitDatabase unit -> NormalisedUnitDbLoc+normalisedUnitDatabaseKey unit_db = normalisedUnitDatabaseKeyOsPath $ unitDatabasePath unit_db++-- | Normalise the unit database location and drop trailing path separators.+--+-- This ensures that two databases that point to the same location can be cached.+--+-- We need to remove trailing slash from the 'OsPath' before calculating @$pkgroot@ (Fix #16360)+normalisedUnitDatabaseKeyOsPath :: OsPath -> NormalisedUnitDbLoc+normalisedUnitDatabaseKeyOsPath db_path =+  NormalisedUnitDbLoc $ OsPath.dropTrailingPathSeparator $ OsPath.normalise db_path++-- | Get the root location of a unit database.+-- Used to replace @$pkgroot@ variables in the 'GenericUnitInfo'.+unitDatabaseRoot :: OsPath -> OsPath+unitDatabaseRoot p =+  let+    NormalisedUnitDbLoc np = normalisedUnitDatabaseKeyOsPath p+  in+    OsPath.takeDirectory np++-- ----------------------------------------------------------------------------+--+-- Merging databases+--++-- | For each unit, a mapping from uid -> i indicates that this+-- unit was brought into GHC by the ith @-package-db@ flag on+-- the command line.  We use this mapping to make sure we prefer+-- units that were defined later on the command line, if there+-- is an ambiguity.+type UnitPrecedenceMap = UniqMap UnitId Int++-- | Given a list of databases, merge them together, where+-- units with the same unit id in later databases override+-- earlier ones.  This does NOT check if the resulting database+-- makes sense (that's done by 'validateDatabase').+mergeDatabases :: Logger -> [UnitDatabase UnitId]+               -> IO (UnitInfoMap, UnitPrecedenceMap)+mergeDatabases logger = foldM merge (emptyUniqMap, emptyUniqMap) . zip [1..]+  where+    merge (pkg_map, prec_map) (i, UnitDatabase db_path db) = do+      debugTraceMsg logger 2 $+          text "loading package database" <+> ppr db_path+      when (logVerbAtLeast logger 2) $+        forM_ (Set.toList override_set) $ \pkg ->+            debugTraceMsg logger 2 $+                text "package" <+> ppr pkg <+>+                text "overrides a previously defined package"+      return (pkg_map', prec_map')+     where+      db_map = mk_pkg_map db+      mk_pkg_map = listToUniqMap . map (\p -> (unitId p, p))++      -- The set of UnitIds which appear in both db and pkgs.  These are the+      -- ones that get overridden.  Compute this just to give some+      -- helpful debug messages at -v2+      override_set :: Set UnitId+      override_set = Set.intersection (nonDetUniqMapToKeySet db_map)+                                      (nonDetUniqMapToKeySet pkg_map)++      -- Now merge the sets together (NB: in case of duplicate,+      -- first argument preferred)+      pkg_map' :: UnitInfoMap+      pkg_map' = pkg_map `plusUniqMap` db_map++      prec_map' :: UnitPrecedenceMap+      prec_map' = prec_map `plusUniqMap` (mapUniqMap (const i) db_map)++-- | This sorts a list of packages, putting "preferred" packages first.+-- See 'compareByPreference' for the semantics of "preference".+sortByPreference :: UnitPrecedenceMap -> [UnitInfo] -> [UnitInfo]+sortByPreference prec_map = sortBy (flip (compareByPreference prec_map))++-- | Returns 'GT' if @pkg@ should be preferred over @pkg'@ when picking+-- which should be "active".  Here is the order of preference:+--+--      1. First, prefer the latest version+--      2. If the versions are the same, prefer the package that+--      came in the latest package database.+--+-- Pursuant to #12518, we could change this policy to, for example, remove+-- the version preference, meaning that we would always prefer the units+-- in later unit database.+compareByPreference+    :: UnitPrecedenceMap+    -> UnitInfo+    -> UnitInfo+    -> Ordering+compareByPreference prec_map pkg pkg'+  = case comparing unitPackageVersion pkg pkg' of+        GT -> GT+        EQ | Just prec  <- lookupUniqMap prec_map (unitId pkg)+           , Just prec' <- lookupUniqMap prec_map (unitId pkg')+           -- Prefer the unit from the later DB flag (i.e., higher+           -- precedence)+           -> compare prec prec'+           | otherwise+           -> EQ+        LT -> LT++-- -----------------------------------------------------------------------------+-- Reading the unit database(s)++data UnitDbConfig = UnitDbConfig+  { unitDbConfigFlagsDB :: [PackageDBFlag]+  , unitDbConfigProgramName :: String+  , unitDbConfigDBName :: FilePath+  , unitDbConfigPlatformArchOS :: ArchOS+  , unitDbConfigGlobalDB :: FilePath+  , unitDbConfigGHCDir :: FilePath+  }++getUnitDbRefs :: UnitDbConfig -> IO [PkgDbRef]+getUnitDbRefs cfg = do+  let system_conf_refs = [UserPkgDb, GlobalPkgDb]++  e_pkg_path <- tryIO (getEnv $ map toUpper (unitDbConfigProgramName cfg) ++ "_PACKAGE_PATH")+  let base_conf_refs = case e_pkg_path of+        Left _ -> system_conf_refs+        Right path+         | Just (xs, x) <- snocView path, isSearchPathSeparator x+         -> map PkgDbPath (OsPath.splitSearchPath (OsPath.unsafeEncodeUtf xs)) ++ system_conf_refs+         | otherwise+         -> map PkgDbPath (OsPath.splitSearchPath (OsPath.unsafeEncodeUtf path))++  -- Apply the package DB-related flags from the command line to get the+  -- final list of package DBs.+  --+  -- Notes on ordering:+  --  * The list of flags is reversed (later ones first)+  --  * We work with the package DB list in "left shadows right" order+  --  * and finally reverse it at the end, to get "right shadows left"+  --+  return $ reverse (foldr doFlag base_conf_refs (unitDbConfigFlagsDB cfg))+ where+  doFlag (PackageDB p) dbs = p : dbs+  doFlag NoUserPackageDB dbs = filter isNotUser dbs+  doFlag NoGlobalPackageDB dbs = filter isNotGlobal dbs+  doFlag ClearPackageDBs _ = []++  isNotUser UserPkgDb = False+  isNotUser _ = True++  isNotGlobal GlobalPkgDb = False+  isNotGlobal _ = True++-- | Return the path of a package database from a 'PkgDbRef'. Return 'Nothing'+-- when the user database filepath is expected but the latter doesn't exist.+--+-- NB: This logic is reimplemented in Cabal, so if you change it,+-- make sure you update Cabal. (Or, better yet, dump it in the+-- compiler info so Cabal can use the info.)+resolveUnitDatabase :: UnitDbConfig -> PkgDbRef -> IO (Maybe OsPath)+resolveUnitDatabase cfg GlobalPkgDb = return $ Just $ OsPath.unsafeEncodeUtf $ unitDbConfigGlobalDB cfg+resolveUnitDatabase cfg UserPkgDb = runMaybeT $ do+  dir <- versionedAppDir (unitDbConfigProgramName cfg) (unitDbConfigPlatformArchOS cfg)+  let pkgconf = dir </> unitDbConfigDBName cfg+  exist <- tryMaybeT $ doesDirectoryExist pkgconf+  if exist then return (OsPath.unsafeEncodeUtf pkgconf) else mzero+resolveUnitDatabase _ (PkgDbPath name) = return $ Just name++-- | Read the 'UnitDatabase' at the given location.+readUnitDatabase :: Logger -> UnitDbConfig -> OsPath -> IO (UnitDatabase UnitId)+readUnitDatabase logger cfg conf_file = do+  isdir <- OsPath.doesDirectoryExist conf_file++  proto_pkg_configs <-+    if isdir+       then readDirStyleUnitInfo conf_file+       else do+            isfile <- OsPath.doesFileExist conf_file+            if isfile+               then do+                 mpkgs <- tryReadOldFileStyleUnitInfo+                 case mpkgs of+                   Just pkgs -> return pkgs+                   Nothing   -> throwGhcExceptionIO $ InstallationError $+                      "ghc no longer supports single-file style package " +++                      "databases (" ++ show conf_file +++                      ") use 'ghc-pkg init' to create the database with " +++                      "the correct format."+               else throwGhcExceptionIO $ InstallationError $+                      "can't find a package database at " ++ show conf_file++  let+      top_dir = OsPath.unsafeEncodeUtf (unitDbConfigGHCDir cfg)+      pkgroot = unitDatabaseRoot conf_file+      pkg_configs1 = map (mungeUnitInfo top_dir pkgroot . mapUnitInfo (\(UnitKey x) -> UnitId x) . mkUnitKeyInfo)+                         proto_pkg_configs+  --+  return $ UnitDatabase conf_file pkg_configs1+  where+    readDirStyleUnitInfo :: OsPath -> IO [DbUnitInfo]+    readDirStyleUnitInfo conf_dir = do+      let filename = conf_dir OsPath.</> (OsPath.unsafeEncodeUtf "package.cache")+      cache_exists <- OsPath.doesFileExist filename+      if cache_exists+        then do+          debugTraceMsg logger 2 $ text "Using binary package database:" <+> ppr filename+          readPackageDbForGhc (OsPath.unsafeDecodeUtf filename)+        else do+          -- If there is no package.cache file, we check if the database is not+          -- empty by inspecting if the directory contains any .conf file. If it+          -- does, something is wrong and we fail. Otherwise we assume that the+          -- database is empty.+          debugTraceMsg logger 2 $ text "There is no package.cache in"+                      <+> ppr conf_dir+                       <> text ", checking if the database is empty"+          db_empty <- all (not . OsPath.isSuffixOf (OsPath.unsafeEncodeUtf ".conf"))+                   <$> OsPath.getDirectoryContents conf_dir+          if db_empty+            then do+              debugTraceMsg logger 3 $ text "There are no .conf files in"+                          <+> ppr conf_dir <> text ", treating"+                          <+> text "package database as empty"+              return []+            else+              throwGhcExceptionIO $ InstallationError $+                "there is no package.cache in " ++ show conf_dir +++                " even though package database is not empty"+++    -- Single-file style package dbs have been deprecated for some time, but+    -- it turns out that Cabal was using them in one place. So this is a+    -- workaround to allow older Cabal versions to use this newer ghc.+    -- We check if the file db contains just "[]" and if so, we look for a new+    -- dir-style db in conf_file.d/, ie in a dir next to the given file.+    -- We cannot just replace the file with a new dir style since Cabal still+    -- assumes it's a file and tries to overwrite with 'writeFile'.+    -- ghc-pkg also cooperates with this workaround.+    tryReadOldFileStyleUnitInfo = do+      content <- readFile (OsPath.unsafeDecodeUtf conf_file) `catchIO` \_ -> return ""+      if take 2 content == "[]"+        then do+          let conf_dir = conf_file OsPath.<.> OsPath.unsafeEncodeUtf "d"+          direxists <- OsPath.doesDirectoryExist conf_dir+          if direxists+             then do debugTraceMsg logger 2 (text "Ignoring old file-style db and trying:" <+> ppr conf_dir)+                     liftM Just (readDirStyleUnitInfo conf_dir)+             else return (Just []) -- ghc-pkg will create it when it's updated+        else return Nothing++mungeUnitInfo :: OsPath -> OsPath+                   -> UnitInfo -> UnitInfo+mungeUnitInfo top_dir pkgroot =+    mungeDynLibFields+  . mungeUnitInfoPaths (ST.pack (OsPath.unsafeDecodeUtf top_dir)) (ST.pack (OsPath.unsafeDecodeUtf pkgroot))++mungeDynLibFields :: UnitInfo -> UnitInfo+mungeDynLibFields pkg =+    pkg {+      unitLibraryDynDirs = case unitLibraryDynDirs pkg of+         [] -> unitLibraryDirs pkg+         ds -> ds+    }
+ GHC/Unit/External/Index.hs view
@@ -0,0 +1,442 @@+{-# LANGUAGE LambdaCase #-}+-- | The 'UnitIndex' is a 'UnitEnv' wide data structure that shares+-- external unit information across the 'UnitState' of all home units+-- (e.g., 'HomeUnitEnv') in a particular 'UnitEnv'.+--+-- It caches already read unit databases, all processed 'UnitInfo's and+-- the 'WireMap'.+--+-- This module is meant to be imported as @Index@.+--+-- A short overview of how the different types here related to 'UnitState', 'UnitEnv'+-- and the 'HomeUnitEnv'.+--+-- ┌─────────┐+-- │ UnitEnv │+-- └────┬────┘+--      ├───────────────────────┐+--      │                       │+-- ┌────▼──────┐          ┌─────▼─────┐+-- │HomeUnitEnv│          │ UnitIndex ├────────────────┐+-- └────┬──────┘          └───────────┘                │+--      │                                              │+--      │      Reads cached unit DBs                   │+-- ┌────▼──────┐          ┌─────────────────────┐      │+-- │ UnitState ├──────────>ExternalUnitDatabases◄──────┤+-- └────┬──┬───┘          └─────────────────────┘      │+--      │  └───────────────────────┐                   │+--      │   Writes new UnitInfos   │                   │+--      │   during initialisation  │                   │+-- ┌────▼────────┐        ┌────────v──────────┐        │+-- │ UnitInfoMap │        │ GlobalUnitInfoMap ◄────────┘+-- └────┬────────┘        └────────^──────────┘+--      │                          │+--      └──────────────────────────┘+--          UnitInfoMap references+--          GlobalUnitInfoMap values+--          (All UnitInfos are shared)+--+-- Open arrow @A ───> B@: A uses B.+-- Closed arrow @A ◄─── B@: A is a field of B.+--+-- Also, see Note [Sharing 'UnitInfo's across the 'UnitEnv'] for more technical discussion+-- about sharing 'UnitInfo's.+module GHC.Unit.External.Index (+  -- * The 'UnitIndexCache'.+  -- A mutable wrapper around 'UnitIndex'+  UnitIndexCache(..),+  initUnitIndexCache,+  readUnitIndex,+  modifyUnitIndexCache,+  clearUnitIndexCache,+  cacheExternalUnitDatabase,+  readExternalUnitDatabases,+  readExternalUnitDatabase,+  -- * 'UnitIndex'+  UnitIndex,+  emptyUnitIndex,+  wiringMap,+  unwiringMap,+  globalUnits,+  externalUnitDatabases,+  setWireMap,+  wireMapExists,+  addUnitInfoMap,+  -- * 'GlobalUnitInfoMap'+  GlobalUnitInfoMap,+  lookupGlobalUnitInfoMap,+  emptyGlobalUnitInfoMap,+  mkGlobalUnitInfoMap,+  -- * 'GlobalUnitKey'+  GlobalUnitKey,+  UnitAbiHash,+  mkGlobalUnitKey,+  globalUnitKeyFromUnitInfo,+  -- * Wired-in units+  setupWiredInUnits,+  updateWiredInUnitIndex,+  unwireUnit,+  updateWiredInUnits,+  updateWiredInUnitsInUnitInfo,+  updateWiredInUnitIdInModule,+  -- * Reading external unit databases into the 'UnitIndexCache'+  readOrGetUnitDatabase,+  readUnitDatabases,+) where++import GHC.Prelude++import GHC.Data.OsPath+import GHC.Data.ShortText qualified as ST+import GHC.Types.Unique.Map+import GHC.Unit.Database+import GHC.Unit.External.Database+import GHC.Unit.External.Visibility+import GHC.Unit.External.Wired+import GHC.Unit.Info+import GHC.Unit.Types+import GHC.Utils.Logger++import Control.Monad (liftM)+import Data.Either+import Data.IORef (IORef)+import Data.IORef qualified as IORef+import Data.Map.Strict (Map)+import Data.Map.Strict qualified as Map+import Data.Maybe (catMaybes)++-- ----------------------------------------------------------------------------+-- UnitIndex+-- ----------------------------------------------------------------------------++-- | Mutable version of 'UnitIndex'.+--+-- The 'UnitIndexCache' ensures that all calls to 'initUnits' will+-- share the 'UnitInfo' if it is possible.+--+-- To share the 'UnitInfo', the 'UnitInfo' needs to be fully-resolved, i.e., its wired-in+-- dependencies and modules need to be replaced with the 'UnitId' of the wired-in unit.+-- Thus, the 'UnitIndexCache' caches both the global 'WireMap' and the 'UnitInfoMap'.+--+-- The 'WireMap' is globally valid, as other parts of the compiler rely on the fact+-- that only one instance of wired-in units is used.+--+-- Memory Invariant: The 'UnitIndexCache' is the root object for retaining fully-resolved+-- 'UnitInfo'. 'UnitState' is expected to reference only 'UnitInfo's from the 'UnitIndexCache'.+-- There is exactly one fully-resolved 'UnitInfo' alive for each external unit per unit database.+--+-- A second instance may or may not be stored in the 'externalUnitDatabases', which represent the+-- in-memory cache of the on-disk unit databases.+newtype UnitIndexCache = UnitIndexCache+  { uic_index :: IORef UnitIndex+  }++initUnitIndexCache :: IO UnitIndexCache+initUnitIndexCache =+  UnitIndexCache <$> IORef.newIORef emptyUnitIndex++readUnitIndex :: UnitIndexCache -> IO UnitIndex+readUnitIndex uic =+  IORef.readIORef (uic_index uic)++modifyUnitIndexCache :: UnitIndexCache -> (UnitIndex -> UnitIndex) -> IO ()+modifyUnitIndexCache uic f =+  IORef.modifyIORef' (uic_index uic) f++clearUnitIndexCache :: UnitIndexCache -> IO ()+clearUnitIndexCache uic =+  modifyUnitIndexCache uic (const emptyUnitIndex)++cacheExternalUnitDatabase :: UnitIndexCache -> UnitDatabase UnitId -> IO ()+cacheExternalUnitDatabase uic db =+  modifyUnitIndexCache uic+    (\ ui ->+      ui+        { ui_externalUnitDatabases = insertExternalUnitDatabases db (ui_externalUnitDatabases ui)+        }+    )++readExternalUnitDatabases :: UnitIndexCache -> IO (ExternalUnitDatabases UnitId)+readExternalUnitDatabases uic =+  externalUnitDatabases <$> readUnitIndex uic++readExternalUnitDatabase :: UnitIndexCache -> OsPath -> IO (Maybe (UnitDatabase UnitId))+readExternalUnitDatabase uic path = do+  dbs <- readExternalUnitDatabases uic+  pure $ lookupExternalUnitDatabases path dbs++-- | Global index for external units that can be shared across multiple 'HomeUnitEnv's.+--+-- Allows sharing of the 'WireMap' and 'UnitInfo's that are stored in the 'UnitState'+-- of each 'HomeUnitEnv'.+--+-- See Note [Sharing 'UnitInfo's across the 'UnitEnv'] for details about memory usage.+data UnitIndex = UnitIndex+  { ui_wireMap :: !WireMap+    -- ^ A mapping from database unit keys to wired in unit ids.+    --+    -- At the moment, the 'WireMap' is global, there can only be one version of+    -- a wired-in package.+  , ui_unwireMap :: !UnwireMap+    -- ^ A mapping from wired in unit ids to unit keys from the database.+    --+    -- At the moment, the 'UnwireMap' is global, there can only be one version of+    -- a wired-in package.+  , ui_unitInfoMap :: !GlobalUnitInfoMap+    -- ^ A global map for all fully-resolved 'UnitInfo's.+    --+    -- See Note [Sharing 'UnitInfo's across the 'UnitEnv'] for more details+    -- what we use this for and what a fully-resolved 'UnitInfo' is.+  , ui_externalUnitDatabases :: !(ExternalUnitDatabases UnitId)+    -- ^ Cache the already processed unit databases in-memory.+    --+    -- These 'GenericUnitInfo's have their paths resolved, e.g., no @${pkgroot}@ is+    -- present any more.+  }++-- | Get the 'WireMap'.+--+-- At the moment, the 'WireMap' is global, there can only be one version of+-- a wired-in package.+wiringMap :: UnitIndex -> WireMap+wiringMap = ui_wireMap++-- | Get the 'UnwireMap'.+--+-- At the moment, the 'UnwireMap' is global, there can only be one version of+-- a wired-in package.+unwiringMap :: UnitIndex -> UnwireMap+unwiringMap = ui_unwireMap++-- | Access the already processed unit databases.+externalUnitDatabases :: UnitIndex -> ExternalUnitDatabases UnitId+externalUnitDatabases = ui_externalUnitDatabases++-- | Access the global map of fully-resolved 'UnitInfo's.+--+-- A 'UnitInfo' is fully-resolved, if its dependencies were updated to reference the+-- wired-in packages (e.g., 'wiringMap') and the wired-in packages are updated.+-- Further, the 'UnitInfo' is based on the 'ExternalUnitDatabases' results, resolving+-- variables such as @${pkgroot}@ in paths.+--+-- See Note [Sharing 'UnitInfo's across the 'UnitEnv'] for why this is helpful.+globalUnits :: UnitIndex -> GlobalUnitInfoMap+globalUnits = ui_unitInfoMap++emptyUnitIndex :: UnitIndex+emptyUnitIndex = UnitIndex+  { ui_wireMap = emptyWireMap+  , ui_unwireMap = emptyUnwireMap+  , ui_unitInfoMap = emptyGlobalUnitInfoMap+  , ui_externalUnitDatabases = emptyExternalUnitDatabases+  }++-- | Set the 'WireMap' of 'UnitIndex'.+-- Automatically computes the 'UnwireMap' based on the 'WireMap'.+setWireMap :: WireMap -> UnitIndex -> UnitIndex+setWireMap wired_map unit_index =+  unit_index+    { ui_wireMap = wired_map+    , ui_unwireMap = unwiringMapFromWireMap wired_map+    }++-- | Is there already a 'WireMap' in this 'UnitIndex'?+--+wireMapExists :: UnitIndex -> Bool+wireMapExists unit_index =+  not $ isWireMapEmpty (ui_wireMap unit_index)++addUnitInfoMap :: UnitInfoMap -> UnitIndex -> UnitIndex+addUnitInfoMap unit_info_map unit_index =+  unit_index+    { ui_unitInfoMap =+        -- Order should not matter, either it is exactly the same 'UnitInfo',+        -- or a new one.+        GlobalUnitInfoMap $ plusUniqMap_C Map.union newEntriesMap oldMap+    }+  where+    GlobalUnitInfoMap newEntriesMap = mkGlobalUnitInfoMap $ nonDetUniqMapToList unit_info_map+    GlobalUnitInfoMap oldMap = ui_unitInfoMap unit_index++-- ----------------------------------------------------------------------------+-- GlobalUnitInfoMap+-- ----------------------------------------------------------------------------++type UnitAbiHash = ST.ShortText++-- | Like a 'UnitInfoMap' but stores all 'UnitInfo's.+--+-- It is keyed by the 'UnitId' and the 'UnitInfo's 'UnitAbiHash'.+-- In modern cabal, there should never be a conflict of 'UnitId's, as cabal+-- hashes the Abi, dependency hashes, source hashes and more.+--+-- However, a user can choose a conflicting 'UnitId', causing a conflict after all.+-- We use the 'UnitAbiHash' for disambiguation. If both 'UnitId' and 'UnitAbiHash' are+-- identical in separate unit databases, we can assume they are the same unit, according+-- to the documentation of GHC.+newtype GlobalUnitInfoMap = GlobalUnitInfoMap (UniqMap UnitId (Map UnitAbiHash UnitInfo))++-- | Lookup the 'UnitInfo' in the 'GlobalUnitInfoMap'.+--+-- This does not check whether the 'GlobalUnitKey' refers to a unit that needs to be resolved+-- in the 'WireMap'.+-- For example, if the 'UnitId' is @ghc-internal-<version>@ (and @ghc-internal@ is a wired-in package),+-- then 'lookupGlobalUnitInfoMap' won't find it, as in the 'GlobalUnitInfoMap', the key is @ghc-internal@.+lookupGlobalUnitInfoMap :: GlobalUnitKey -> GlobalUnitInfoMap -> Maybe UnitInfo+lookupGlobalUnitInfoMap (GlobalUnitKey uid abiHash) (GlobalUnitInfoMap globalMap) =+  case lookupUniqMap globalMap uid of+    Nothing -> Nothing+    Just sameUnitId -> Map.lookup abiHash sameUnitId++mkGlobalUnitInfoMap :: [(UnitId, UnitInfo)] -> GlobalUnitInfoMap+mkGlobalUnitInfoMap unitInfos =+  GlobalUnitInfoMap $ listToUniqMap_C Map.union (map mkEntry unitInfos)+ where+  mkEntry (uid, v) = (uid, Map.singleton (unitAbiHash v) v)++emptyGlobalUnitInfoMap :: GlobalUnitInfoMap+emptyGlobalUnitInfoMap = GlobalUnitInfoMap emptyUniqMap++-- ----------------------------------------------------------------------------+-- GlobalUnitKey+-- ----------------------------------------------------------------------------++-- | A 'GlobalUnitKey' is a key that can globally identify a 'UnitInfo', not just+-- in the 'UnitInfoMap'.+--+-- The 'UnitId' and 'UnitAbiHash' uniquely identify a 'UnitInfo'.+data GlobalUnitKey =+  GlobalUnitKey+    !UnitId -- ^ Unit Id of the 'UnitInfo'+    !UnitAbiHash -- ^ ABI hash of the 'UnitInfo'++globalUnitKeyFromUnitInfo :: UnitInfo -> GlobalUnitKey+globalUnitKeyFromUnitInfo ui = mkGlobalUnitKey (unitId ui) (unitAbiHash ui)++mkGlobalUnitKey :: UnitId -> UnitAbiHash -> GlobalUnitKey+mkGlobalUnitKey = GlobalUnitKey++-- -----------------------------------------------------------------------------+-- Wired-in units+--+-- See Note [Wired-in units] in GHC.Unit.Types++-- | Find the wired-in units in the given '[UnitInfo]' if there isn't already+-- one in the 'UnitIndexCache'. If there is, simply return the existing 'WireMap'.+-- Otherwise, update the 'wiringMap' in the 'UnitIndexCache'+setupWiredInUnits :: Logger -> UnitPrecedenceMap -> [UnitInfo] -> VisibilityMap -> UnitIndexCache -> IO WireMap+setupWiredInUnits logger prec_map pkgs vis_map unit_index = do+  ui <- readUnitIndex unit_index+  if not $ wireMapExists ui+    then do+      wmap <- findWiredInUnits logger prec_map pkgs vis_map+      modifyUnitIndexCache unit_index (setWireMap wmap)+      pure wmap+    else do+      pure $ ui_wireMap ui++-- | Resolve the wired-in units in the '[UnitInfo]'.+-- If the fully-resolved can be found in 'UnitIndexCache', then we use it.+-- If the resolved 'UnitInfo' is new, we immediately cache it in the 'UnitIndexCache'.+-- We return the fully-resolved 'UnitInfo' list in the same order as provided.+updateWiredInUnitIndex :: WireMap -> [UnitInfo] -> UnitIndexCache -> IO [UnitInfo]+updateWiredInUnitIndex wired_map pkgs unit_index = do+  ui <- readUnitIndex unit_index+  let+    all_pkgs = updateWiredInUnits wired_map (ui_unitInfoMap ui) pkgs+    (new_pkgs', _pkgs_set) = partitionEithers all_pkgs+  -- Make sure we force the 'UnitInfo' here.+  -- Otherwise, we will retain a reference to the old 'UnitInfo'+  new_pkgs <- traverse evaluateUnitInfoLists new_pkgs'+  modifyUnitIndexCache unit_index (addUnitInfoMap $ mkUnitInfoMap new_pkgs)+  pure (map (either id id) all_pkgs)++-- | Given a wired-in 'Unit', "unwire" it into the 'Unit'+-- that it was recorded as in the package database.+unwireUnit :: UnitIndex -> Unit -> Unit+unwireUnit state uid@(RealUnit (Definite def_uid)) =+    maybe uid (RealUnit . Definite) (lookupUnwireMap def_uid (unwiringMap state))+unwireUnit _ uid = uid++updateWiredInUnits :: WireMap -> GlobalUnitInfoMap -> [UnitInfo] -> [Either UnitInfo UnitInfo]+updateWiredInUnits wiredInMap knownInfos pkgs =+  map (updateWiredInUnitsInUnitInfo wiredInMap knownInfos) pkgs++updateWiredInUnitsInUnitInfo :: WireMap -> GlobalUnitInfoMap -> UnitInfo -> Either UnitInfo UnitInfo+updateWiredInUnitsInUnitInfo wiredInMap knownInfos pkg =+  let+    upd_wired_in_pkg wiredInUnitId pkg =+      pkg { unitId         = wiredInUnitId+          , unitInstanceOf = wiredInUnitId+              -- every non instantiated unit is an instance of+              -- itself (required by Backpack...)+              --+              -- See Note [About units] in GHC.Unit+          }++    upd_deps pkg = pkg {+          unitDepends = map (upd_wired_in wiredInMap) (unitDepends pkg),+          unitExposedModules+            = map (\(k,v) -> (k, fmap (updateWiredInUnitIdInModule wiredInMap) v))+                  (unitExposedModules pkg)+        }++    -- First check whether this is a wired-in unit.+    -- If it is, we need to use the wired-in 'UnitId' for looking up the UnitInfo in the+    -- 'GlobalUnitInfoMap'. We also update the 'UnitInfo' to use the wired-in unitId, as that's+    -- how we are going to use it, if it isn't already present in the 'GlobalUnitInfoMap'.+    -- Otherwise, we simply look up the 'UnitInfo' in the 'GlobalUnitInfoMap'.+    (candidatePkg, key) =+      case lookupWireMap (unitId pkg) wiredInMap of+        Just wiredIn -> (upd_wired_in_pkg wiredIn pkg, mkGlobalUnitKey wiredIn (unitAbiHash pkg))+        Nothing      -> (pkg, globalUnitKeyFromUnitInfo pkg)+  in+    -- If the UnitInfo is not already present in the 'GlobalUnitInfoMap', we need to update+    -- all references to wired-in units.+    case lookupGlobalUnitInfoMap key knownInfos of+      Just ui -> Right ui+      Nothing -> Left (upd_deps candidatePkg)++-- Helper functions for rewiring Module and Unit.  These+-- rewrite Units of modules in wired-in packages to the form known to the+-- compiler, as described in Note [Wired-in units] in GHC.Unit.Types.+--+-- For instance, base-4.9.0.0 will be rewritten to just base, to match+-- what appears in GHC.Builtin.Names.++updateWiredInUnitIdInModule :: WireMap -> Module -> Module+updateWiredInUnitIdInModule wiredInMap (Module uid m) = Module (upd_wired_in_uid wiredInMap uid) m++upd_wired_in_uid :: WireMap -> Unit -> Unit+upd_wired_in_uid wiredInMap u = case u of+   HoleUnit -> HoleUnit+   RealUnit (Definite uid) -> RealUnit (Definite (upd_wired_in wiredInMap uid))+   VirtUnit indef_uid ->+      VirtUnit $ mkInstantiatedUnit+        (instUnitInstanceOf indef_uid)+        (map (\(x,y) -> (x,updateWiredInUnitIdInModule wiredInMap y)) (instUnitInsts indef_uid))++upd_wired_in :: WireMap -> UnitId -> UnitId+upd_wired_in wiredInMap key+    | Just key' <- lookupWireMap key wiredInMap = key'+    | otherwise = key++-- -----------------------------------------------------------------------------+-- Reading the unit database(s) into the 'UnitIndexCache'++readUnitDatabases :: Logger -> UnitIndexCache -> UnitDbConfig -> IO [UnitDatabase UnitId]+readUnitDatabases logger db_cache cfg = do+  conf_refs <- getUnitDbRefs cfg+  confs     <- liftM catMaybes $ mapM (resolveUnitDatabase cfg) conf_refs+  mapM (readOrGetUnitDatabase logger db_cache cfg) confs++-- | Get the cached 'UnitDatabase' or read the 'UnitDatabase' at the given location.+readOrGetUnitDatabase :: Logger -> UnitIndexCache -> UnitDbConfig -> OsPath -> IO (UnitDatabase UnitId)+readOrGetUnitDatabase logger db_cache cfg conf_file =+  readExternalUnitDatabase db_cache conf_file >>= \ case+    Nothing -> do+      new_db <- readUnitDatabase logger cfg conf_file+      cacheExternalUnitDatabase db_cache new_db+      pure new_db+    Just db ->+      pure db
+ GHC/Unit/External/ModuleOrigin.hs view
@@ -0,0 +1,110 @@+module GHC.Unit.External.ModuleOrigin (+  ModuleOrigin(..),+  fromExposedModules,+  fromReexportedModules,+  fromFlag,+  originVisible,+  originEmpty,+) where++import Data.Semigroup qualified as Semigroup+import GHC.Prelude+import GHC.Unit.External.Validate+import GHC.Unit.Info+import GHC.Utils.Outputable+import GHC.Utils.Panic++-- | Given a module name, there may be multiple ways it came into scope,+-- possibly simultaneously.  This data type tracks all the possible ways+-- it could have come into scope.  Warning: don't use the record functions,+-- they're partial!+data ModuleOrigin =+    -- | Module is hidden, and thus never will be available for import.+    -- (But maybe the user didn't realize), so we'll still keep track+    -- of these modules.)+    ModHidden++    -- | Module is unavailable because the unit is unusable.+  | ModUnusable !UnusableUnit++    -- | Module is public, and could have come from some places.+  | ModOrigin {+        -- | @Just False@ means that this module is in+        -- someone's @exported-modules@ list, but that package is hidden;+        -- @Just True@ means that it is available; @Nothing@ means neither+        -- applies.+        fromOrigUnit :: Maybe Bool+        -- | Is the module available from a reexport of an exposed package?+        -- There could be multiple.+      , fromExposedReexport :: [UnitInfo]+        -- | Is the module available from a reexport of a hidden package?+      , fromHiddenReexport :: [UnitInfo]+        -- | Did the module export come from a package flag? (ToDo: track+        -- more information.+      , fromPackageFlag :: Bool+      }++instance Outputable ModuleOrigin where+    ppr ModHidden = text "hidden module"+    ppr (ModUnusable _) = text "unusable module"+    ppr (ModOrigin e res rhs f) = sep (punctuate comma (+        (case e of+            Nothing -> []+            Just False -> [text "hidden package"]+            Just True -> [text "exposed package"]) +++        (if null res+            then []+            else [text "reexport by" <+>+                    sep (map (ppr . mkUnit) res)]) +++        (if null rhs+            then []+            else [text "hidden reexport by" <+>+                    sep (map (ppr . mkUnit) rhs)]) +++        (if f then [text "package flag"] else [])+        ))++-- | Smart constructor for a module which is in @exposed-modules@.  Takes+-- as an argument whether or not the defining package is exposed.+fromExposedModules :: Bool -> ModuleOrigin+fromExposedModules e = ModOrigin (Just e) [] [] False++-- | Smart constructor for a module which is in @reexported-modules@.  Takes+-- as an argument whether or not the reexporting package is exposed, and+-- also its 'UnitInfo'.+fromReexportedModules :: Bool -> UnitInfo -> ModuleOrigin+fromReexportedModules True pkg = ModOrigin Nothing [pkg] [] False+fromReexportedModules False pkg = ModOrigin Nothing [] [pkg] False++-- | Smart constructor for a module which was bound by a package flag.+fromFlag :: ModuleOrigin+fromFlag = ModOrigin Nothing [] [] True++instance Semigroup ModuleOrigin where+    x@(ModOrigin e res rhs f) <> y@(ModOrigin e' res' rhs' f') =+        ModOrigin (g e e') (res ++ res') (rhs ++ rhs') (f || f')+      where g (Just b) (Just b')+                | b == b'   = Just b+                | otherwise = pprPanic "ModOrigin: package both exposed/hidden" $+                    text "x: " <> ppr x $$ text "y: " <> ppr y+            g Nothing x = x+            g x Nothing = x++    x <> y = pprPanic "ModOrigin: module origin mismatch" $+                 text "x: " <> ppr x $$ text "y: " <> ppr y++instance Monoid ModuleOrigin where+    mempty = ModOrigin Nothing [] [] False+    mappend = (Semigroup.<>)++-- | Is the name from the import actually visible? (i.e. does it cause+-- ambiguity, or is it only relevant when we're making suggestions?)+originVisible :: ModuleOrigin -> Bool+originVisible ModHidden = False+originVisible (ModUnusable _) = False+originVisible (ModOrigin b res _ f) = b == Just True || not (null res) || f++-- | Are there actually no providers for this module?  This will never occur+-- except when we're filtering based on package imports.+originEmpty :: ModuleOrigin -> Bool+originEmpty (ModOrigin Nothing [] [] False) = True+originEmpty _ = False
+ GHC/Unit/External/Providers.hs view
@@ -0,0 +1,186 @@+module GHC.Unit.External.Providers (+  ModuleNameProvidersMap,+  pprModuleMap,+  mkModuleNameProvidersMap,+  mkUnusableModuleNameProvidersMap,+) where++import GHC.Prelude++import GHC.Data.Maybe+import GHC.Types.Unique+import GHC.Types.Unique.FM+import GHC.Types.Unique.Map+import GHC.Unit.External.ModuleOrigin+import GHC.Unit.External.Query+import GHC.Unit.External.Validate+import GHC.Unit.External.Visibility+import GHC.Unit.Info+import GHC.Unit.Module+import GHC.Utils.Error+import GHC.Utils.Logger+import GHC.Utils.Outputable+import GHC.Utils.Panic++-- | Map from 'ModuleName' to a set of module providers (i.e. a 'Module' and+-- its 'ModuleOrigin').+--+-- NB: the set is in fact a 'Map Module ModuleOrigin', probably to keep only one+-- origin for a given 'Module'++type ModuleNameProvidersMap =+    UniqMap ModuleName (UniqMap Module ModuleOrigin)++-- | Show the mapping of modules to where they come from.+pprModuleMap :: ModuleNameProvidersMap -> SDoc+pprModuleMap mod_map =+  vcat (map pprLine (nonDetUniqMapToList mod_map))+    where+      pprLine (m,e) = ppr m $$ nest 50 (vcat (map (pprEntry m) (nonDetUniqMapToList e)))+      pprEntry :: Outputable a => ModuleName -> (Module, a) -> SDoc+      pprEntry m (m',o)+        | m == moduleName m' = ppr (moduleUnit m') <+> parens (ppr o)+        | otherwise = ppr m' <+> parens (ppr o)++-- -----------------------------------------------------------------------------+-- | Makes the mapping from ModuleName to package info++-- Slight irritation: we proceed by leafing through everything+-- in the installed package database, which makes handling indefinite+-- packages a bit bothersome.++mkModuleNameProvidersMap+  :: Logger+  -> Bool+  -> UnitInfoMap+  -> VisibilityMap+  -> ModuleNameProvidersMap+mkModuleNameProvidersMap logger allowVirtualUnits pkg_map vis_map =+    -- What should we fold on?  Both situations are awkward:+    --+    --    * Folding on the visibility map means that we won't create+    --      entries for packages that aren't mentioned in vis_map+    --      (e.g., hidden packages, causing #14717)+    --+    --    * Folding on pkg_map is awkward because if we have an+    --      Backpack instantiation, we need to possibly add a+    --      package from pkg_map multiple times to the actual+    --      ModuleNameProvidersMap.  Also, we don't really want+    --      definite package instantiations to show up in the+    --      list of possibilities.+    --+    -- So what will we do instead?  We'll extend vis_map with+    -- entries for every definite (for non-Backpack) and+    -- indefinite (for Backpack) package, so that we get the+    -- hidden entries we need.+    nonDetFoldUniqMap extend_modmap emptyMap vis_map_extended+ where+  vis_map_extended = {- preferred -} default_vis `plusUniqMap` vis_map++  default_vis = listToUniqMap+                  [ (mkUnit pkg, mempty)+                  | (_, pkg) <- nonDetUniqMapToList pkg_map+                  -- Exclude specific instantiations of an indefinite+                  -- package+                  , unitIsIndefinite pkg || null (unitInstantiations pkg)+                  ]++  emptyMap = emptyUniqMap+  setOrigins m os = fmap (const os) m+  extend_modmap (uid, UnitVisibility { uv_expose_all = b, uv_renamings = rns }) modmap+    = addListTo modmap theBindings+   where+    pkg = unit_lookup uid++    theBindings :: [(ModuleName, UniqMap Module ModuleOrigin)]+    theBindings = newBindings b rns++    newBindings :: Bool+                -> [(ModuleName, ModuleName)]+                -> [(ModuleName, UniqMap Module ModuleOrigin)]+    newBindings e rns  = es e ++ hiddens ++ map rnBinding rns++    rnBinding :: (ModuleName, ModuleName)+              -> (ModuleName, UniqMap Module ModuleOrigin)+    rnBinding (orig, new) = (new, setOrigins origEntry fromFlag)+     where origEntry = case lookupUFM esmap orig of+            Just r -> r+            Nothing -> throwGhcException (CmdLineError (renderWithContext+                        (log_default_user_context (logFlags logger))+                        (text "package flag: could not find module name" <+>+                            ppr orig <+> text "in package" <+> ppr pk)))++    es :: Bool -> [(ModuleName, UniqMap Module ModuleOrigin)]+    es e = do+     (m, exposedReexport) <- exposed_mods+     let (pk', m', origin') =+          case exposedReexport of+           Nothing -> (pk, m, fromExposedModules e)+           Just (Module pk' m') ->+              (pk', m', fromReexportedModules e pkg)+     return (m, mkModMap pk' m' origin')++    esmap :: UniqFM ModuleName (UniqMap Module ModuleOrigin)+    esmap = listToUFM (es False) -- parameter here doesn't matter, orig will+                                 -- be overwritten++    hiddens = [(m, mkModMap pk m ModHidden) | m <- hidden_mods]++    pk = mkUnit pkg+    unit_lookup uid = lookupUnit' allowVirtualUnits pkg_map uid+                        `orElse` pprPanic "unit_lookup" (ppr uid)++    exposed_mods = unitExposedModules pkg+    hidden_mods  = unitHiddenModules pkg++-- | Make a 'ModuleNameProvidersMap' covering a set of unusable packages.+mkUnusableModuleNameProvidersMap :: UnusableUnits -> ModuleNameProvidersMap+mkUnusableModuleNameProvidersMap unusables =+    nonDetFoldUniqMap extend_modmap emptyUniqMap unusables+ where+    extend_modmap (_uid, (unit_info, reason)) modmap = addListTo modmap bindings+      where bindings :: [(ModuleName, UniqMap Module ModuleOrigin)]+            bindings = exposed ++ hidden++            origin_reexport =  ModUnusable (UnusableUnit unit reason True)+            origin_normal   =  ModUnusable (UnusableUnit unit reason False)+            unit = mkUnit unit_info++            exposed = map get_exposed exposed_mods+            hidden = [(m, mkModMap unit m origin_normal) | m <- hidden_mods]++            -- with re-exports, c:Foo can be reexported from two (or more)+            -- unusable packages:+            --  Foo -> a:Foo (unusable reason A) -> c:Foo+            --      -> b:Foo (unusable reason B) -> c:Foo+            --+            -- We must be careful to not record the following (#21097):+            --  Foo -> c:Foo (unusable reason A)+            --      -> c:Foo (unusable reason B)+            -- But:+            --  Foo -> a:Foo (unusable reason A)+            --      -> b:Foo (unusable reason B)+            --+            get_exposed (mod, Just _) = (mod, mkModMap unit mod origin_reexport)+            get_exposed (mod, _) = (mod, mkModMap unit mod origin_normal)+              -- in the reexport case, we create a virtual module that doesn't+              -- exist but we don't care as it's only used as a key in the map.++            exposed_mods = unitExposedModules unit_info+            hidden_mods  = unitHiddenModules  unit_info++-- | Add a list of key/value pairs to a nested map.+--+-- The outer map is processed with 'Data.Map.Strict' to prevent memory leaks+-- when reloading modules in GHCi (see #4029). This ensures that each+-- value is forced before installing into the map.+addListTo :: (Monoid a, Ord k1, Ord k2, Uniquable k1, Uniquable k2)+          => UniqMap k1 (UniqMap k2 a)+          -> [(k1, UniqMap k2 a)]+          -> UniqMap k1 (UniqMap k2 a)+addListTo = foldl' merge+  where merge m (k, v) = addToUniqMap_C (plusUniqMap_C mappend) m k v++-- | Create a singleton module mapping+mkModMap :: Unit -> ModuleName -> ModuleOrigin -> UniqMap Module ModuleOrigin+mkModMap pkg mod = unitUniqMap (mkModule pkg mod)
+ GHC/Unit/External/Query.hs view
@@ -0,0 +1,41 @@+module GHC.Unit.External.Query (+  -- * Query the 'UnitInfoMap'+  lookupUnit',+  lookupUnitId',+) where++import GHC.Prelude++import GHC.Types.Unique.Map+import GHC.Unit.External.Substitution+import GHC.Unit.Info+import GHC.Unit.Module++-- | A more specialized interface, which doesn't require a 'UnitState' (so it+-- can be used while we're initializing 'DynFlags')+--+-- Parameters:+--    * a boolean specifying whether or not to look for on-the-fly renamed interfaces+--    * a 'UnitInfoMap'+lookupUnit' :: Bool -> UnitInfoMap -> Unit -> Maybe UnitInfo+lookupUnit' allowOnTheFlyInst pkg_map u = case u of+   HoleUnit   -> error "Hole unit"+   RealUnit i -> lookupUniqMap pkg_map (unDefinite i)+   VirtUnit i+      | allowOnTheFlyInst+      -> -- lookup UnitInfo of the indefinite unit to be instantiated and+         -- instantiate it on-the-fly+         fmap (renameUnitInfo pkg_map (instUnitInsts i))+           (lookupUniqMap pkg_map (instUnitInstanceOf i))++      | otherwise+      -> -- lookup UnitInfo by virtual UnitId. This is used to find indefinite+         -- units. Even if they are real, installed units, they can't use the+         -- `RealUnit` constructor (it is reserved for definite units) so we use+         -- the `VirtUnit` constructor.+         lookupUniqMap pkg_map (virtualUnitId i)+++-- | Find the unit we know about with the given unit id, if any+lookupUnitId' :: UnitInfoMap -> UnitId -> Maybe UnitInfo+lookupUnitId' db uid = lookupUniqMap db uid
+ GHC/Unit/External/Substitution.hs view
@@ -0,0 +1,61 @@+module GHC.Unit.External.Substitution (+  -- * Substitution and module renaming+  ShHoleSubst,+  renameHoleModule',+  renameHoleUnit',+  renameUnitInfo,+) where++import GHC.Prelude++import GHC.Unit.Module+import GHC.Unit.Info+import GHC.Types.Unique.FM+import GHC.Types.Unique.DFM+import GHC.Types.Unique.DSet++-- -----------------------------------------------------------------------------+-- Module renaming++-- | Substitution on module variables, mapping module names to module+-- identifiers.+type ShHoleSubst = ModuleNameEnv Module++-- | Rename a 'UnitInfo' according to some module instantiation.+renameUnitInfo :: UnitInfoMap -> [(ModuleName, Module)] -> UnitInfo -> UnitInfo+renameUnitInfo pkg_map insts conf =+    let hsubst = listToUFM insts+        smod  = renameHoleModule' pkg_map hsubst+        new_insts = map (\(k,v) -> (k,smod v)) (unitInstantiations conf)+    in conf {+        unitInstantiations = new_insts,+        unitExposedModules = map (\(mod_name, mb_mod) -> (mod_name, fmap smod mb_mod))+                             (unitExposedModules conf)+    }+++-- | Like 'renameHoleModule', but requires only 'UnitInfoMap'+-- so it can be used by "GHC.Unit.State".+renameHoleModule' :: UnitInfoMap -> ShHoleSubst -> Module -> Module+renameHoleModule' pkg_map env m+  | not (isHoleModule m) =+        let uid = renameHoleUnit' pkg_map env (moduleUnit m)+        in mkModule uid (moduleName m)+  | Just m' <- lookupUFM env (moduleName m) = m'+  -- NB m = <Blah>, that's what's in scope.+  | otherwise = m++-- | Like 'renameHoleUnit', but requires only 'UnitInfoMap'+-- so it can be used by "GHC.Unit.State".+renameHoleUnit' :: UnitInfoMap -> ShHoleSubst -> Unit -> Unit+renameHoleUnit' pkg_map env uid =+    case uid of+      (VirtUnit+        InstantiatedUnit{ instUnitInstanceOf = cid+                        , instUnitInsts      = insts+                        , instUnitHoles      = fh })+          -> if isNullUFM (intersectUFM_C const (udfmToUfm (getUniqDSet fh)) env)+                then uid+                else mkVirtUnit cid+                          (map (\(k,v) -> (k, renameHoleModule' pkg_map env v)) insts)+      _ -> uid
+ GHC/Unit/External/Validate.hs view
@@ -0,0 +1,384 @@+{-# LANGUAGE LambdaCase #-}+module GHC.Unit.External.Validate (+  -- * Validation of unit databases+  validateDatabase,+  reportUnusable,+  UnusableUnits,+  UnusableUnit(..),+  UnusableUnitReason(..),+  pprReason,+  -- * Package resolver+  findPackages,+  selectPackages,+  -- * Unit database closure validation+  UnitErr(..),+  mayThrowUnitErr,+  closeUnitDeps,+  closeUnitDeps',+  -- * Utils+  ignoreUnits,+  pprFlag,+) where++import GHC.Prelude++import Control.Monad+import Data.Graph (SCC (..), stronglyConnComp)+import Data.List (partition)+import GHC.Data.Maybe+import GHC.Driver.DynFlags+import GHC.Types.Unique.Map+import GHC.Unit.External.Database+import GHC.Unit.External.Query+import GHC.Unit.External.Substitution+import GHC.Unit.Info+import GHC.Unit.Types+import GHC.Utils.Error+import GHC.Utils.Logger+import GHC.Utils.Outputable+import GHC.Utils.Outputable qualified as Outputable+import GHC.Utils.Panic++-- -----------------------------------------------------------------------------+-- Database validation++-- | Validates a database, removing unusable units from it+-- (this includes removing units that the user has explicitly+-- ignored.)  Our general strategy:+--+-- 1. Remove all broken units (dangling dependencies)+-- 2. Remove all units that are cyclic+-- 3. Apply ignore flags+-- 4. Remove all units which have deps with mismatching ABIs+--+validateDatabase :: [IgnorePackageFlag] -> UnitInfoMap+                 -> (UnitInfoMap, UnusableUnits, [SCC UnitInfo])+validateDatabase flagsIgnored pkg_map1 =+    (pkg_map5, unusable, sccs)+  where+    ignore_flags = reverse flagsIgnored -- (unitConfigFlagsIgnored cfg)++    -- Compute the reverse dependency index+    index = reverseDeps pkg_map1++    -- Helper function+    mk_unusable mk_err dep_matcher m uids =+      listToUniqMap [ (unitId pkg, (pkg, mk_err (dep_matcher m pkg)))+                    | pkg <- uids+                    ]++    -- Find broken units+    directly_broken = filter (not . null . depsNotAvailable pkg_map1)+                             (nonDetEltsUniqMap pkg_map1)+    (pkg_map2, broken) = removeUnits (map unitId directly_broken) index pkg_map1+    unusable_broken = mk_unusable BrokenDependencies depsNotAvailable pkg_map2 broken++    -- Find recursive units+    sccs = stronglyConnComp [ (pkg, unitId pkg, unitDepends pkg)+                            | pkg <- nonDetEltsUniqMap pkg_map2 ]+    getCyclicSCC (CyclicSCC vs) = map unitId vs+    getCyclicSCC (AcyclicSCC _) = []+    (pkg_map3, cyclic) = removeUnits (concatMap getCyclicSCC sccs) index pkg_map2+    unusable_cyclic = mk_unusable CyclicDependencies depsNotAvailable pkg_map3 cyclic++    -- Apply ignore flags+    directly_ignored = ignoreUnits ignore_flags (nonDetEltsUniqMap pkg_map3)+    (pkg_map4, ignored) = removeUnits (nonDetKeysUniqMap directly_ignored) index pkg_map3+    unusable_ignored = mk_unusable IgnoredDependencies depsNotAvailable pkg_map4 ignored++    -- Knock out units whose dependencies don't agree with ABI+    -- (i.e., got invalidated due to shadowing)+    directly_shadowed = filter (not . null . depsAbiMismatch pkg_map4)+                               (nonDetEltsUniqMap pkg_map4)+    (pkg_map5, shadowed) = removeUnits (map unitId directly_shadowed) index pkg_map4+    unusable_shadowed = mk_unusable ShadowedDependencies depsAbiMismatch pkg_map5 shadowed++    -- combine all unusables. The order is important for shadowing.+    -- plusUniqMapList folds using plusUFM which is right biased (opposite of+    -- Data.Map.union) so the head of the list should be the least preferred+    unusable = plusUniqMapList [ unusable_shadowed+                               , unusable_cyclic+                               , unusable_broken+                               , unusable_ignored+                               , directly_ignored+                               ]+++type UnusableUnits = UniqMap UnitId (UnitInfo, UnusableUnitReason)++-- | A unusable unit module origin+data UnusableUnit = UnusableUnit+  { uuUnit        :: !Unit               -- ^ Unusable unit+  , uuReason      :: !UnusableUnitReason -- ^ Reason+  , uuIsReexport  :: !Bool               -- ^ Is the "module" a reexport?+  }++-- | The reason why a unit is unusable.+data UnusableUnitReason+  = -- | We ignored it explicitly using @-ignore-package@.+    IgnoredWithFlag+    -- | This unit transitively depends on a unit that was never present+    -- in any of the provided databases.+  | BrokenDependencies   [UnitId]+    -- | This unit transitively depends on a unit involved in a cycle.+    -- Note that the list of 'UnitId' reports the direct dependencies+    -- of this unit that (transitively) depended on the cycle, and not+    -- the actual cycle itself (which we report separately at high verbosity.)+  | CyclicDependencies   [UnitId]+    -- | This unit transitively depends on a unit which was ignored.+  | IgnoredDependencies  [UnitId]+    -- | This unit transitively depends on a unit which was+    -- shadowed by an ABI-incompatible unit.+  | ShadowedDependencies [UnitId]++instance Outputable UnusableUnitReason where+    ppr IgnoredWithFlag = text "[ignored with flag]"+    ppr (BrokenDependencies uids)   = brackets (text "broken" <+> ppr uids)+    ppr (CyclicDependencies uids)   = brackets (text "cyclic" <+> ppr uids)+    ppr (IgnoredDependencies uids)  = brackets (text "ignored" <+> ppr uids)+    ppr (ShadowedDependencies uids) = brackets (text "shadowed" <+> ppr uids)++pprReason :: SDoc -> UnusableUnitReason -> SDoc+pprReason pref reason = case reason of+  IgnoredWithFlag ->+      pref <+> text "ignored due to an -ignore-package flag"+  BrokenDependencies deps ->+      pref <+> text "unusable due to missing dependencies:" $$+        nest 2 (hsep (map ppr deps))+  CyclicDependencies deps ->+      pref <+> text "unusable due to cyclic dependencies:" $$+        nest 2 (hsep (map ppr deps))+  IgnoredDependencies deps ->+      pref <+> text ("unusable because the -ignore-package flag was used to " +++                     "ignore at least one of its dependencies:") $$+        nest 2 (hsep (map ppr deps))+  ShadowedDependencies deps ->+      pref <+> text "unusable due to shadowed dependencies:" $$+        nest 2 (hsep (map ppr deps))++reportUnusable :: Logger -> UnusableUnits -> IO ()+reportUnusable logger pkgs = when (logVerbAtLeast logger 2) $ mapM_ report (nonDetUniqMapToList pkgs)+  where+    report (ipid, (_, reason)) =+       debugTraceMsg logger 2 $+         pprReason+           (text "package" <+> ppr ipid <+> text "is") reason++-- -----------------------------------------------------------------------------+-- Package Finding++-- | Like 'selectPackages', but doesn't return a list of unmatched+-- packages.  Furthermore, any packages it returns are *renamed*+-- if the 'UnitArg' has a renaming associated with it.+findPackages :: UnitPrecedenceMap+             -> UnitInfoMap+             -> PackageArg -> [UnitInfo]+             -> UnusableUnits+             -> Either [(UnitInfo, UnusableUnitReason)]+                [UnitInfo]+findPackages prec_map pkg_map arg pkgs unusable+  = let ps = mapMaybe (finder arg) pkgs+    in if null ps+        then Left (mapMaybe (\(x,y) -> finder arg x >>= \x' -> return (x',y))+                            (nonDetEltsUniqMap unusable))+        else Right (sortByPreference prec_map ps)+  where+    finder (PackageArg str) p+      = if matchingStr str p+          then Just p+          else Nothing+    finder (UnitIdArg uid) p+      = case uid of+          RealUnit (Definite iuid)+            | iuid == unitId p+            -> Just p+          VirtUnit inst+            | instUnitInstanceOf inst == unitId p+            -> Just (renameUnitInfo pkg_map (instUnitInsts inst) p)+          _ -> Nothing++selectPackages :: UnitPrecedenceMap -> PackageArg -> [UnitInfo]+               -> UnusableUnits+               -> Either [(UnitInfo, UnusableUnitReason)]+                  ([UnitInfo], [UnitInfo])+selectPackages prec_map arg pkgs unusable+  = let matches = matching arg+        (ps,rest) = partition matches pkgs+    in if null ps+        then Left (filter (matches.fst) (nonDetEltsUniqMap unusable))+        else Right (sortByPreference prec_map ps, rest)++-- -----------------------------------------------------------------------------+-- Ignore units++ignoreUnits :: [IgnorePackageFlag] -> [UnitInfo] -> UnusableUnits+ignoreUnits flags pkgs = listToUniqMap (concatMap doit flags)+  where+  doit (IgnorePackage str) =+     case partition (matchingStr str) pkgs of+         (ps, _) -> [ (unitId p, (p, IgnoredWithFlag))+                    | p <- ps ]+        -- missing unit is not an error for -ignore-package,+        -- because a common usage is to -ignore-package P as+        -- a preventative measure just in case P exists.++-- A package named on the command line can either include the+-- version, or just the name if it is unambiguous.+matchingStr :: String -> UnitInfo -> Bool+matchingStr str p+        =  str == unitPackageIdString p+        || str == unitPackageNameString p++matchingId :: UnitId -> UnitInfo -> Bool+matchingId uid p = uid == unitId p++matching :: PackageArg -> UnitInfo -> Bool+matching (PackageArg str) = matchingStr str+matching (UnitIdArg (RealUnit (Definite uid))) = matchingId uid+matching (UnitIdArg _)  = \_ -> False -- TODO: warn in this case++-- ----------------------------------------------------------------------------+--+-- Closures+--+++-- | Takes a list of UnitIds (and their "parent" dependency, used for error+-- messages), and returns the list with dependencies included, in reverse+-- dependency order (a units appears before those it depends on).+closeUnitDeps :: UnitInfoMap -> [(UnitId,Maybe UnitId)] -> MaybeErr UnitErr [UnitId]+closeUnitDeps pkg_map ps = closeUnitDeps' pkg_map [] ps++-- | Similar to closeUnitDeps but takes a list of already loaded units as an+-- additional argument.+closeUnitDeps' :: UnitInfoMap -> [UnitId] -> [(UnitId,Maybe UnitId)] -> MaybeErr UnitErr [UnitId]+closeUnitDeps' pkg_map current_ids ps = foldM (uncurry . add_unit pkg_map) current_ids ps++-- | Add a UnitId and those it depends on (recursively) to the given list of+-- UnitIds if they are not already in it. Return a list in reverse dependency+-- order (a unit appears before those it depends on).+--+-- The UnitId is looked up in the given UnitInfoMap (to find its dependencies).+-- It it's not found, the optional parent unit is used to return a more precise+-- error message ("dependency of <PARENT>").+add_unit :: UnitInfoMap+            -> [UnitId]+            -> UnitId+            -> Maybe UnitId+            -> MaybeErr UnitErr [UnitId]+add_unit pkg_map ps p mb_parent+  | p `elem` ps = return ps     -- Check if we've already added this unit+  | otherwise   = case lookupUnitId' pkg_map p of+      Nothing   -> Failed (CloseUnitErr p mb_parent)+      Just info -> do+         -- Add the unit's dependents also+         ps' <- foldM add_unit_key ps (unitDepends info)+         return (p : ps')+        where+          add_unit_key xs key+            = add_unit pkg_map xs key (Just p)+data UnitErr+  = CloseUnitErr !UnitId !(Maybe UnitId)+  | PackageFlagErr !PackageFlag ![(UnitInfo,UnusableUnitReason)]+  | TrustFlagErr   !TrustFlag   ![(UnitInfo,UnusableUnitReason)]++mayThrowUnitErr :: MaybeErr UnitErr a -> IO a+mayThrowUnitErr = \case+    Failed e    -> throwGhcExceptionIO+                    $ CmdLineError+                    $ renderWithContext defaultSDocContext+                    $ withPprStyle defaultUserStyle+                    $ ppr e+    Succeeded a -> return a++instance Outputable UnitErr where+    ppr = \case+        CloseUnitErr p mb_parent+            -> (text "unknown unit:" <+> ppr p)+               <> case mb_parent of+                     Nothing     -> Outputable.empty+                     Just parent -> space <> parens (text "dependency of"+                                              <+> ftext (unitIdFS parent))+        PackageFlagErr flag reasons+            -> flag_err (pprFlag flag) reasons++        TrustFlagErr flag reasons+            -> flag_err (pprTrustFlag flag) reasons+      where+        flag_err flag_doc reasons =+            text "cannot satisfy "+            <> flag_doc+            <> (if null reasons then Outputable.empty else text ": ")+            $$ nest 4 (vcat (map ppr_reason reasons) $$+                      text "(use -v for more information)")++        ppr_reason (p, reason) =+            pprReason (ppr (unitId p) <+> text "is") reason+++pprFlag :: PackageFlag -> SDoc+pprFlag flag = case flag of+    HidePackage p   -> text "-hide-package " <> text p+    ExposePackage doc _ _ -> text doc++pprTrustFlag :: TrustFlag -> SDoc+pprTrustFlag flag = case flag of+    TrustPackage p    -> text "-trust " <> text p+    DistrustPackage p -> text "-distrust " <> text p++-- ----------------------------------------------------------------------------+--+-- Utilities on the database+--++-- | A reverse dependency index, mapping an 'UnitId' to+-- the 'UnitId's which have a dependency on it.+type RevIndex = UniqMap UnitId [UnitId]++-- | Compute the reverse dependency index of a unit database.+reverseDeps :: UnitInfoMap -> RevIndex+reverseDeps db = nonDetFoldUniqMap go emptyUniqMap db+  where+    go :: (UnitId, UnitInfo) -> RevIndex -> RevIndex+    go (_uid, pkg) r = foldl' (go' (unitId pkg)) r (unitDepends pkg)+    go' from r to = addToUniqMap_C (++) r to [from]++-- | Given a list of 'UnitId's to remove, a database,+-- and a reverse dependency index (as computed by 'reverseDeps'),+-- remove those units, plus any units which depend on them.+-- Returns the pruned database, as well as a list of 'UnitInfo's+-- that was removed.+removeUnits :: [UnitId] -> RevIndex+               -> UnitInfoMap+               -> (UnitInfoMap, [UnitInfo])+removeUnits uids index m = go uids (m,[])+  where+    go [] (m,pkgs) = (m,pkgs)+    go (uid:uids) (m,pkgs)+        | Just pkg <- lookupUniqMap m uid+        = case lookupUniqMap index uid of+            Nothing    -> go uids (delFromUniqMap m uid, pkg:pkgs)+            Just rdeps -> go (rdeps ++ uids) (delFromUniqMap m uid, pkg:pkgs)+        | otherwise+        = go uids (m,pkgs)++-- | Given a 'UnitInfo' from some 'UnitInfoMap', return all entries in 'depends'+-- which correspond to units that do not exist in the index.+depsNotAvailable :: UnitInfoMap+                 -> UnitInfo+                 -> [UnitId]+depsNotAvailable pkg_map pkg = filter (not . (`elemUniqMap` pkg_map)) (unitDepends pkg)++-- | Given a 'UnitInfo' from some 'UnitInfoMap' return all entries in+-- 'unitAbiDepends' which correspond to units that do not exist, OR have+-- mismatching ABIs.+depsAbiMismatch :: UnitInfoMap+                -> UnitInfo+                -> [UnitId]+depsAbiMismatch pkg_map pkg = map fst . filter (not . abiMatch) $ unitAbiDepends pkg+  where+    abiMatch (dep_uid, abi)+        | Just dep_pkg <- lookupUniqMap pkg_map dep_uid+        = unitAbiHash dep_pkg == abi+        | otherwise+        = False
+ GHC/Unit/External/Visibility.hs view
@@ -0,0 +1,72 @@+module GHC.Unit.External.Visibility (+  VisibilityMap,+  UnitVisibility(..),+) where++import GHC.Prelude++import GHC.Data.FastString+import GHC.Driver.DynFlags+import GHC.Types.Unique.Map+import GHC.Unit.Module+import GHC.Utils.Outputable as Outputable++import Control.Applicative+import Data.Monoid (First (..))+import Data.Semigroup qualified as Semigroup+import Data.Set (Set)+import Data.Set qualified as Set++-- | 'UniqFM' map from 'Unit' to a 'UnitVisibility'.+type VisibilityMap = UniqMap Unit UnitVisibility++-- | 'UnitVisibility' records the various aspects of visibility of a particular+-- 'Unit'.+data UnitVisibility = UnitVisibility+    { uv_expose_all :: Bool+      --  ^ Should all modules in exposed-modules should be dumped into scope?+    , uv_renamings :: [(ModuleName, ModuleName)]+      -- ^ Any custom renamings that should bring extra 'ModuleName's into+      -- scope.+    , uv_package_name :: First FastString+      -- ^ The package name associated with the 'Unit'.  This is used+      -- to implement legacy behavior where @-package foo-0.1@ implicitly+      -- hides any packages named @foo@+    , uv_requirements :: UniqMap ModuleName (Set InstantiatedModule)+      -- ^ The signatures which are contributed to the requirements context+      -- from this unit ID.+    , uv_explicit :: Maybe PackageArg+      -- ^ Whether or not this unit was explicitly brought into scope,+      -- as opposed to implicitly via the 'exposed' fields in the+      -- package database (when @-hide-all-packages@ is not passed.)+    }++instance Outputable UnitVisibility where+    ppr (UnitVisibility {+        uv_expose_all = b,+        uv_renamings = rns,+        uv_package_name = First mb_pn,+        uv_requirements = reqs,+        uv_explicit = explicit+    }) = ppr (b, rns, mb_pn, reqs, explicit)++instance Semigroup UnitVisibility where+    uv1 <> uv2+        = UnitVisibility+          { uv_expose_all = uv_expose_all uv1 || uv_expose_all uv2+          , uv_renamings = uv_renamings uv1 ++ uv_renamings uv2+          , uv_package_name = mappend (uv_package_name uv1) (uv_package_name uv2)+          , uv_requirements = plusUniqMap_C Set.union (uv_requirements uv2) (uv_requirements uv1)+          , uv_explicit = uv_explicit uv1 <|> uv_explicit uv2+          }++instance Monoid UnitVisibility where+    mempty = UnitVisibility+             { uv_expose_all = False+             , uv_renamings = []+             , uv_package_name = First Nothing+             , uv_requirements = emptyUniqMap+             , uv_explicit = Nothing+             }+    mappend = (Semigroup.<>)+
+ GHC/Unit/External/Wired.hs view
@@ -0,0 +1,144 @@+module GHC.Unit.External.Wired (+  -- * 'WireMap'+  WireMap,+  emptyWireMap,+  isWireMapEmpty,+  lookupWireMap,+  listWireMap,+  nonDetFoldWireMap,+  -- * 'UnwireMap'+  UnwireMap,+  emptyUnwireMap,+  lookupUnwireMap,+  unwiringMapFromWireMap,+  -- * Creating 'WireMap'+  findWiredInUnits,+) where++import GHC.Prelude++import GHC.Unit.External.Database+import GHC.Unit.External.Visibility++import GHC.Data.Maybe+import GHC.Types.Unique.Map+import GHC.Unit.Database+import GHC.Unit.Info+import GHC.Unit.Types+import GHC.Utils.Error+import GHC.Utils.Logger+import GHC.Utils.Outputable as Outputable++-- | The 'WireMap' records the mapping from the 'UnitId' of on-disk 'UnitInfo'+-- to the 'UnitId' of the 'wiredInMap'.+--+-- See 'wiredInUnitIds' for the set of wired-in units.+--+newtype WireMap =+  WireMap (UniqMap UnitId UnitId)++emptyWireMap :: WireMap+emptyWireMap = WireMap emptyUniqMap++isWireMapEmpty :: WireMap -> Bool+isWireMapEmpty (WireMap wmap) = isNullUniqMap wmap++lookupWireMap :: UnitId -> WireMap -> Maybe UnitId+lookupWireMap uid (WireMap wmap) = lookupUniqMap wmap uid++listWireMap :: WireMap -> [(UnitId, UnitId)]+listWireMap (WireMap wmap) = nonDetUniqMapToList wmap++nonDetFoldWireMap :: ((UnitId, UnitId) -> b -> b) -> b -> WireMap -> b+nonDetFoldWireMap go z (WireMap uniq) = nonDetFoldUniqMap go z uniq++-- | The reverse of 'WireMap'.+-- Records the mapping from the wired-in 'UnitId' to the on-disk 'UnitId'.+newtype UnwireMap =+  UnwireMap (UniqMap UnitId UnitId)++emptyUnwireMap :: UnwireMap+emptyUnwireMap = UnwireMap emptyUniqMap++unwiringMapFromWireMap :: WireMap -> UnwireMap+unwiringMapFromWireMap (WireMap wired_map) =+  UnwireMap $ listToUniqMap [ (v,k) | (k,v) <- nonDetUniqMapToList wired_map ]++lookupUnwireMap :: UnitId -> UnwireMap -> Maybe UnitId+lookupUnwireMap uid (UnwireMap wmap) = lookupUniqMap wmap uid++-- -----------------------------------------------------------------------------+-- Wired-in units+--+-- See Note [Wired-in units] in GHC.Unit.Types++findWiredInUnits+   :: Logger+   -> UnitPrecedenceMap+   -> [UnitInfo]           -- database+   -> VisibilityMap             -- info on what units are visible+                                -- for wired in selection+   -> IO WireMap   -- map from unit id to wired identity+findWiredInUnits logger prec_map pkgs vis_map = do+  -- Now we must find our wired-in units, and rename them to+  -- their canonical names (eg. base-1.0 ==> base), as described+  -- in Note [Wired-in units] in GHC.Unit.Types+  let+        matches :: UnitInfo -> UnitId -> Bool+        pc `matches` pid = unitPackageName pc == PackageName (unitIdFS pid)++        -- find which package corresponds to each wired-in package+        -- delete any other packages with the same name+        -- update the package and any dependencies to point to the new+        -- one.+        --+        -- When choosing which package to map to a wired-in package+        -- name, we try to pick the latest version of exposed packages.+        -- However, if there are no exposed wired in packages available+        -- (e.g. -hide-all-packages was used), we can't bail: we *have*+        -- to assign a package for the wired-in package: so we try again+        -- with hidden packages included to (and pick the latest+        -- version).+        --+        -- You can also override the default choice by using -ignore-package:+        -- this works even when there is no exposed wired in package+        -- available.+        --+        findWiredInUnit :: [UnitInfo] -> UnitId -> IO (Maybe (UnitId, UnitInfo))+        findWiredInUnit pkgs wired_pkg = firstJustsM [try all_exposed_ps, try all_ps, notfound]+          where+                all_ps = [ p | p <- pkgs, p `matches` wired_pkg ]+                all_exposed_ps = [ p | p <- all_ps, (mkUnit p) `elemUniqMap` vis_map ]++                try ps = case sortByPreference prec_map ps of+                    p:_ -> Just <$> pick p+                    _ -> pure Nothing++                notfound = do+                          debugTraceMsg logger 2 $+                            text "wired-in package "+                                 <> ftext (unitIdFS wired_pkg)+                                 <> text " not found."+                          return Nothing+                pick :: UnitInfo -> IO (UnitId, UnitInfo)+                pick pkg = do+                        debugTraceMsg logger 2 $+                            text "wired-in package "+                                 <> ftext (unitIdFS wired_pkg)+                                 <> text " mapped to "+                                 <> ppr (unitId pkg)+                        return (wired_pkg, pkg)+++  mb_wired_in_pkgs <- mapM (findWiredInUnit pkgs) wiredInUnitIds+  let+        wired_in_pkgs = catMaybes mb_wired_in_pkgs++        wiredInMap :: UniqMap UnitId UnitId+        wiredInMap = listToUniqMap+          [ (unitId realUnitInfo, wiredInUnitId)+          | (wiredInUnitId, realUnitInfo) <- wired_in_pkgs+          , not (unitIsIndefinite realUnitInfo)+          ]++  return $ WireMap wiredInMap
GHC/Unit/Finder.hs view
@@ -42,6 +42,11 @@ import GHC.Unit.Env import GHC.Unit.Types import GHC.Unit.Module+import GHC.Unit.Module.Graph+       (+           HomeModuleNameProvidersMap,+           mgHomeModuleNameProvidersMap+       ) import GHC.Unit.Home import GHC.Unit.Home.Graph (UnitEnvGraph) import qualified GHC.Unit.Home.Graph as HUG@@ -60,15 +65,17 @@  import GHC.Fingerprint import Data.IORef-import System.Directory.OsPath import Control.Applicative ((<|>)) import Control.Monad import Data.Time import qualified Data.Map as M+import GHC.Types.Unique.Map import GHC.Driver.Env import GHC.Driver.Config.Finder-import qualified Data.Set as Set+import GHC.Types.Unique.Set import Data.List.NonEmpty ( NonEmpty (..) )+import Data.Set (Set)+import qualified Data.Set as Set (empty, intersection, difference, null, toList) import qualified System.OsPath as OsPath import qualified Data.List.NonEmpty as NE @@ -151,12 +158,13 @@  findImportedModule :: HscEnv -> ModuleName -> PkgQual -> IO FindResult findImportedModule hsc_env mod pkg_qual =-  let fc        = hsc_FC hsc_env-      mhome_unit = hsc_home_unit_maybe hsc_env-      dflags    = hsc_dflags hsc_env-      fopts     = initFinderOpts dflags+  let fc           = hsc_FC hsc_env+      mb_home_unit = hsc_home_unit_maybe hsc_env+      dflags       = hsc_dflags hsc_env+      fopts        = initFinderOpts dflags   in do-    findImportedModuleNoHsc fc fopts (hsc_unit_env hsc_env) mhome_unit mod pkg_qual+    let home_module_name_providers_map = mgHomeModuleNameProvidersMap (hsc_mod_graph hsc_env)+    findImportedModuleNoHsc fc fopts (hsc_unit_env hsc_env) home_module_name_providers_map mb_home_unit mod pkg_qual  findImportedModuleWithIsBoot :: HscEnv -> ModuleName -> IsBootInterface -> PkgQual -> IO FindResult findImportedModuleWithIsBoot hsc_env mod is_boot pkg_qual = do@@ -169,56 +177,127 @@   :: FinderCache   -> FinderOpts   -> UnitEnv+  -> HomeModuleNameProvidersMap   -> Maybe HomeUnit   -> ModuleName   -> PkgQual   -> IO FindResult-findImportedModuleNoHsc fc fopts ue mhome_unit mod_name mb_pkg =+findImportedModuleNoHsc fc fopts ue home_module_name_providers_map mb_home_unit mod_name mb_pkg =   case mb_pkg of     NoPkgQual  -> unqual_import-    ThisPkg uid | (homeUnitId <$> mhome_unit) == Just uid -> home_import+    ThisPkg uid | (homeUnitId <$> mb_home_unit) == Just uid -> home_import                 | Just os <- lookup uid other_fopts -> home_pkg_import (uid, os)-                | otherwise -> pprPanic "findImportModule" (ppr mod_name $$ ppr mb_pkg $$ ppr (homeUnitId <$> mhome_unit) $$ ppr uid $$ ppr (map fst all_opts))+                | otherwise -> pprPanic "findImportModule" (ppr mod_name $$ ppr mb_pkg $$ ppr (homeUnitId <$> mb_home_unit) $$ ppr uid $$ ppr (map fst all_opts))     OtherPkg _ -> pkg_import   where-    all_opts = case mhome_unit of-                Nothing -> other_fopts-                Just home_unit -> (homeUnitId home_unit, fopts) : other_fopts +    mb_home_unit_id :: Maybe UnitId+    mb_home_unit_id = homeUnitId <$> mb_home_unit -    home_import = case mhome_unit of-                   Just home_unit -> findHomeModule fc fopts home_unit mod_name-                   Nothing -> pure $ NoPackage (panic "findImportedModule: no home-unit")+    all_opts :: [(UnitId, FinderOpts)]+    all_opts = case mb_home_unit_id of+        Nothing           -> other_fopts+        Just home_unit_id -> (home_unit_id, fopts) : other_fopts +    home_import :: IO FindResult+    home_import = case mb_home_unit of+        Just home_unit -> findHomeModule fc fopts home_unit mod_name+        Nothing        -> pure $+                          NoPackage (panic "findImportedModule: no home-unit") +    home_pkg_import :: (UnitId, FinderOpts) -> IO FindResult     home_pkg_import (uid, opts)-      -- If the module is reexported, then look for it as if it was from the perspective-      -- of that package which reexports it.-      | Just real_mod_name <- mod_name `M.lookup` finder_reexportedModules opts =-        findImportedModuleNoHsc fc opts ue (Just $ DefiniteHomeUnit uid Nothing) real_mod_name NoPkgQual-      | mod_name `Set.member` finder_hiddenModules opts =-        return (mkHomeHidden uid)-      | otherwise =-        findHomePackageModule fc opts uid mod_name+        -- If the module is reexported, then look for it as if it was from the+        -- perspective of that package which reexports it.+        | Just real_mod_name+              <- lookupUniqMap (finder_reexportedModules opts) mod_name+            = findImportedModuleNoHsc fc opts ue home_module_name_providers_map+                  (Just $ DefiniteHomeUnit uid Nothing)+                  real_mod_name+                  NoPkgQual+        | elementOfUniqSet mod_name (finder_hiddenModules opts)+            = return (mkHomeHidden uid)+        | otherwise+            = findHomePackageModule fc opts uid mod_name -    -- Do not be smart and change this to `foldr orIfNotFound home_import hs` as-    -- that is not the same!! home_import is first because we need to look within ourselves-    -- first before looking at the packages in order.-    any_home_import = foldr1 orIfNotFound (home_import:| map home_pkg_import other_fopts)+    any_home_import :: IO FindResult+    any_home_import = foldr1 orIfNotFound $+                      home_import :| map home_pkg_import other_fopts+    -- Do not try to be smart and change this to `foldr orIfNotFound home_import+    -- (map home_pkg_import other_fopts)`, as that would not be the same.+    -- `home_import` is first because we need to first look within the current+    -- unit before looking at the other units in order. -    pkg_import    = findExposedPackageModule fc fopts units  mod_name mb_pkg+    pkg_import :: IO FindResult+    pkg_import = findExposedPackageModule fc fopts unit_state mod_name mb_pkg -    unqual_import = any_home_import-                    `orIfNotFound`-                    findExposedPackageModule fc fopts units mod_name NoPkgQual+    unqual_import :: IO FindResult+    unqual_import+        = any_home_import+          `orIfNotFound`+          findExposedPackageModule fc fopts unit_state mod_name NoPkgQual -    units     = case mhome_unit of-                  Nothing -> ue_homeUnitState ue-                  Just home_unit -> HUG.homeUnitEnv_units $ ue_findHomeUnitEnv (homeUnitId home_unit) ue-    hpt_deps :: [UnitId]-    hpt_deps  = homeUnitDepends units-    other_fopts  = map (\uid -> (uid, initFinderOpts (homeUnitEnv_dflags (ue_findHomeUnitEnv uid ue)))) hpt_deps+    unit_state :: UnitState+    unit_state = case mb_home_unit_id of+        Nothing           -> ue_homeUnitState ue+        Just home_unit_id -> HUG.homeUnitEnv_units $+                             ue_findHomeUnitEnv home_unit_id ue +    home_unit_deps :: Set UnitId+    home_unit_deps = homeUnitDepends unit_state++    ranked_home_unit_deps :: [UnitId]+    ranked_home_unit_deps = rankedHomeUnitDeps home_module_name_providers_map+                                               mod_name+                                               home_unit_deps++    other_fopts :: [(UnitId, FinderOpts)]+    other_fopts+        = [+              (uid, opts) |+                  uid <- ranked_home_unit_deps,+                  let opts = initFinderOpts $+                             homeUnitEnv_dflags (ue_findHomeUnitEnv uid ue)+          ]++-- | Yields the unit IDs from the given set as a list with those that refer to+-- providers of the given home module name coming first. This is to prioritize+-- such providers during module finding.+rankedHomeUnitDeps :: HomeModuleNameProvidersMap+                   -> ModuleName+                   -> Set UnitId+                   -> [UnitId]+rankedHomeUnitDeps _ _ home_unit_deps | Set.null home_unit_deps+    = []+-- The special handling of the situation where the dependency set is empty does+-- not change the result, but it avoids triggering evaluation of the module+-- graph. This is particularly important in one-shot mode, where the module+-- graph is not needed. Computing it nevertheless would result in a, possibly+-- dramatic, increase of memory usage. Worse, GHC would erroneously look for the+-- sources of modules, which would, for example, cause test `boot1` to fail with+-- the following error message:+--+--     B.hs:3:1: error: [GHC-87110]+--         Could not find module ‘A’.+--         Use -v to see a list of the files searched for.+--       |+--     3 | import {-# source #-} A+--       | ^^^^^^^^^^^^^^^^^^^^^^^+rankedHomeUnitDeps home_module_name_providers_map mod_name home_unit_deps+    = Set.toList cached_deps ++ Set.toList uncached_deps+    where++    cached_providers :: Set UnitId+    cached_providers = lookupWithDefaultUniqMap home_module_name_providers_map+                                                Set.empty+                                                mod_name++    cached_deps :: Set UnitId+    cached_deps = Set.intersection home_unit_deps cached_providers++    uncached_deps :: Set UnitId+    uncached_deps = Set.difference home_unit_deps cached_providers+ -- | Locate a plugin module requested by the user, for a compiler -- plugin.  This consults the same set of exposed packages as -- 'findImportedModule', unless @-hide-all-plugin-packages@ or@@ -235,15 +314,15 @@ findPluginModule hsc_env mod_name = do   let fc = hsc_FC hsc_env   let units = hsc_units hsc_env-  let mhome_unit = hsc_home_unit_maybe hsc_env-  findPluginModuleNoHsc fc (initFinderOpts (hsc_dflags hsc_env)) units mhome_unit mod_name+  let mb_home_unit = hsc_home_unit_maybe hsc_env+  findPluginModuleNoHsc fc (initFinderOpts (hsc_dflags hsc_env)) units mb_home_unit mod_name   -- | A version of findExactModule which takes the exact parts of the HscEnv it needs -- directly. findExactModuleNoHsc :: FinderCache -> FinderOpts -> UnitEnvGraph FinderOpts -> UnitState -> Maybe HomeUnit -> InstalledModule -> IsBootInterface -> IO InstalledFindResult-findExactModuleNoHsc fc fopts other_fopts unit_state mhome_unit mod is_boot = do-  res <- case mhome_unit of+findExactModuleNoHsc fc fopts other_fopts unit_state mb_home_unit mod is_boot = do+  res <- case mb_home_unit of     Just home_unit      | isHomeInstalledModule home_unit mod         -> findInstalledHomeModule fc fopts (homeUnitId home_unit) (moduleName mod)@@ -337,9 +416,9 @@                                          , fr_suggestions = []})      LookupMultiple rs ->        return (FoundMultiple rs)-     LookupHidden pkg_hiddens mod_hiddens ->+     LookupHidden fr_pkgs_hidden mod_hiddens ->        return (NotFound{ fr_paths = [], fr_pkg = Nothing-                       , fr_pkgs_hidden = map (moduleUnit.fst) pkg_hiddens+                       , fr_pkgs_hidden                        , fr_mods_hidden = map (moduleUnit.fst) mod_hiddens                        , fr_unusables = []                        , fr_suggestions = [] })@@ -782,7 +861,7 @@ findObjectLinkableMaybe :: Module -> ModLocation -> IO (Maybe Linkable) findObjectLinkableMaybe mod locn    = do let obj_fn = ml_obj_file locn-        maybe_obj_time <- modificationTimeIfExists obj_fn+        maybe_obj_time <- modificationTimeIfExists (ml_obj_file_ospath locn)         case maybe_obj_time of           Nothing -> return Nothing           Just obj_time -> liftM Just (findObjectLinkable mod obj_fn obj_time)@@ -794,4 +873,3 @@   pure (Linkable obj_time mod (NE.singleton (DotO obj_fn ModuleObject)))   -- We used to look for _stub.o files here, but that was a bug (#706)   -- Now GHC merges the stub.o into the main .o (#3687)-
GHC/Unit/Finder/Types.hs view
@@ -12,12 +12,13 @@ import GHC.Unit import GHC.Data.OsPath import qualified Data.Map as M+import GHC.Types.Unique.Map import GHC.Fingerprint import GHC.Platform.Ways import GHC.Unit.Env  import GHC.Data.FastString-import qualified Data.Set as Set+import GHC.Types.Unique.Set  -- | The 'FinderCache' maps modules to the result of -- searching for that module. It records the results of searching for@@ -68,7 +69,7 @@       , fr_mods_hidden :: [Unit]           -- ^ Module is in these units,                                            --   but the *module* is hidden -      , fr_pkgs_hidden :: [Unit]           -- ^ Module is in these units,+      , fr_pkgs_hidden :: [UnitInfo]       -- ^ Module is in these units,                                            --   but the *unit* is hidden          -- | Module is in these units, but it is unusable@@ -101,8 +102,8 @@       -- that have a similar name.   , finder_workingDirectory :: Maybe OsPath   , finder_thisPackageName  :: Maybe FastString-  , finder_hiddenModules    :: Set.Set ModuleName-  , finder_reexportedModules :: M.Map ModuleName ModuleName -- Reverse mapping, if you are looking for this name then look for this module.+  , finder_hiddenModules    :: !(UniqSet ModuleName)+  , finder_reexportedModules :: !(UniqMap ModuleName ModuleName) -- Reverse mapping, if you are looking for this name then look for this module.   , finder_hieDir :: Maybe OsPath   , finder_hieSuf :: OsString   , finder_hiDir :: Maybe OsPath
GHC/Unit/Home/Graph.hs view
@@ -128,16 +128,6 @@   { homeUnitEnv_units     :: !UnitState       -- ^ External units -  , homeUnitEnv_unit_dbs :: !(Maybe [UnitDatabase UnitId])-      -- ^ Stack of unit databases for the target platform.-      ---      -- This field is populated with the result of `initUnits`.-      ---      -- 'Nothing' means the databases have never been read from disk.-      ---      -- Usually we don't reload the databases from disk if they are-      -- cached, even if the database flags changed!-   , homeUnitEnv_dflags :: DynFlags     -- ^ The dynamic flag settings   , homeUnitEnv_hpt :: HomePackageTable@@ -164,10 +154,9 @@     -- ^ Home-unit   } -mkHomeUnitEnv :: UnitState -> Maybe [UnitDatabase UnitId] -> DynFlags -> HomePackageTable -> Maybe HomeUnit -> HomeUnitEnv-mkHomeUnitEnv us dbs dflags hpt home_unit = HomeUnitEnv+mkHomeUnitEnv :: UnitState -> DynFlags -> HomePackageTable -> Maybe HomeUnit -> HomeUnitEnv+mkHomeUnitEnv us dflags hpt home_unit = HomeUnitEnv   { homeUnitEnv_units = us-  , homeUnitEnv_unit_dbs = dbs   , homeUnitEnv_dflags = dflags   , homeUnitEnv_hpt = hpt   , homeUnitEnv_home_unit = home_unit@@ -229,15 +218,18 @@ -- If the argument unit is not present in the graph returns Nothing. transitiveHomeDeps :: UnitId -> HomeUnitGraph -> Maybe [UnitId] transitiveHomeDeps uid hug = case lookupHugUnitId uid hug of-  Nothing -> Nothing+  Nothing  -> Nothing   Just hue -> Just $-    Set.toList (loop (Set.singleton uid) (homeUnitDepends (homeUnitEnv_units hue)))+              Set.toList $+              loop (Set.singleton uid)+                   (Set.toList (homeUnitDepends (homeUnitEnv_units hue)))     where       loop acc [] = acc       loop acc (uid:uids)         | uid `Set.member` acc = loop acc uids         | otherwise =-          let hue = homeUnitDepends+          let hue = Set.toList+                    . homeUnitDepends                     . homeUnitEnv_units                     . expectJust                     $ lookupHugUnitId uid hug@@ -359,7 +351,11 @@ hugSCCs :: HomeUnitGraph -> [SCC UnitId] hugSCCs hug = sccs where   mkNode :: (UnitId, HomeUnitEnv) -> Node UnitId UnitId-  mkNode (uid, hue) = DigraphNode uid uid (homeUnitDepends (homeUnitEnv_units hue))+  mkNode (uid, hue) = DigraphNode+                          uid+                          uid+                          (Set.toList (homeUnitDepends (homeUnitEnv_units hue)))+   nodes = map mkNode (Map.toList $ unitEnv_graph hug)    sccs = stronglyConnCompFromEdgedVerticesOrd nodes
GHC/Unit/Info.hs view
@@ -5,11 +5,15 @@    ( GenericUnitInfo (..)    , GenUnitInfo    , UnitInfo+   , UnitInfoMap+   , mkUnitInfoMap    , UnitKey (..)    , UnitKeyInfo    , mkUnitKeyInfo    , mapUnitInfo    , mkUnitPprInfo+   , evaluateUnitInfoLists+   , seqUnitInfoLists     , mkUnit @@ -50,6 +54,8 @@ import Data.Version import Data.Bifunctor import Data.List (isPrefixOf, stripPrefix)+import GHC.Types.Unique.Map+import Control.Exception (evaluate)   -- | Information about an installed unit@@ -70,6 +76,10 @@ -- UnitId) type UnitInfo    = GenUnitInfo UnitId +-- | Information about multiple installed units (units are identified by their internal+-- UnitId)+type UnitInfoMap = UniqMap UnitId UnitInfo+ -- | Convert a DbUnitInfo (read from a package database) into `UnitKeyInfo` mkUnitKeyInfo :: DbUnitInfo -> UnitKeyInfo mkUnitKeyInfo = mapGenericUnitInfo@@ -241,3 +251,42 @@          expandTag t | null t = ""                     | otherwise = '_':t++-- | Create a Map UnitId UnitInfo+--+-- For each instantiated unit, we add two map keys:+--    * the real unit id+--    * the virtual unit id made from its instantiation+--+-- We do the same thing for fully indefinite units (which are "instantiated"+-- with module holes).+--+mkUnitInfoMap :: [UnitInfo] -> UnitInfoMap+mkUnitInfoMap infos = foldl' add emptyUniqMap infos+  where+   mkVirt      p = virtualUnitId (mkInstantiatedUnit (unitInstanceOf p) (unitInstantiations p))+   add pkg_map p+      | not (null (unitInstantiations p))+      = addToUniqMap (addToUniqMap pkg_map (mkVirt p) p)+                     (unitId p) p+      | otherwise+      = addToUniqMap pkg_map (unitId p) p++-- | Evaluate the lists in 'UnitInfo' to avoid retaining references to old 'UnitInfo's.+evaluateUnitInfoLists :: UnitInfo -> IO UnitInfo+evaluateUnitInfoLists ui = evaluate (ui `seqUnitInfoLists` ui)++-- | Evaluate the lists in 'UnitInfo' to avoid retaining references to old 'UnitInfo's.+-- This effectively ensures that all list elements in 'UnitInfo' are fully to whnf.+seqUnitInfoLists :: UnitInfo -> b -> b+seqUnitInfoLists ui b =+  unitImportDirs ui `seqList`+  unitIncludeDirs ui `seqList`+  unitLibraryDirs ui `seqList`+  unitExtDepFrameworkDirs ui `seq`+  unitHaddockInterfaces ui `seq`+  unitHaddockHTMLs ui `seqList`+  unitLibraryDynDirs ui `seqList`+  unitDepends ui `seqList`+  unitExposedModules ui `seqList`+  b
GHC/Unit/Module/Deps.hs view
@@ -2,6 +2,9 @@ {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE ExplicitNamespaces #-} {-# LANGUAGE DerivingVia #-}++{-# OPTIONS_GHC -Wwarn=incomplete-record-selectors #-}+ -- | Dependencies and Usage of a module module GHC.Unit.Module.Deps    ( Dependencies(dep_direct_mods@@ -19,6 +22,7 @@    , noDependencies    , pprDeps    , Usage (..)+   , stableUsageCmp    , HomeModImport (..)    , HomeModImportedAvails (..)    , ImportAvails (..)@@ -45,6 +49,7 @@ import GHC.Utils.Binary import GHC.Utils.Outputable +import Data.Function (on) import Data.List (sortBy, sort, partition) import Data.Set (Set) import qualified Data.Set as Set@@ -463,6 +468,42 @@             hash <- get bh             return UsageHomeModuleInterface { usg_mod_name = mod, usg_unit_id = uid, usg_iface_hash = hash }           i -> error ("Binary.get(Usage): " ++ show i)++-- | Compares 'Usage's by constructor and, if the constructors are the same, by+--   identifying strings, to achieve a predictable ordering.+stableUsageCmp :: Usage -> Usage -> Ordering+stableUsageCmp+    usage1@UsagePackageModule {}+    usage2@UsagePackageModule {}+    = (compare `on` usg_mod) usage1 usage2+stableUsageCmp+    usage1@UsageHomeModule {}+    usage2@UsageHomeModule {}+    = (compare `on` Module <$> usg_unit_id <*> usg_mod_name) usage1 usage2+stableUsageCmp+    usage1@UsageFile {}+    usage2@UsageFile {}+    = (lexicalCompareFS `on` usg_file_path) usage1 usage2+stableUsageCmp+    usage1@UsageHomeModuleInterface {}+    usage2@UsageHomeModuleInterface {}+    = (compare `on` Module <$> usg_unit_id <*> usg_mod_name) usage1 usage2+stableUsageCmp+    usage1@UsageMergedRequirement {}+    usage2@UsageMergedRequirement {}+    = (compare `on` usg_mod) usage1 usage2+stableUsageCmp+    usage1+    usage2+    = (compare `on` constructorIndex) usage1 usage2+    where++    constructorIndex :: Usage -> Int+    constructorIndex UsagePackageModule       {} = 0+    constructorIndex UsageHomeModule          {} = 1+    constructorIndex UsageFile                {} = 2+    constructorIndex UsageHomeModuleInterface {} = 3+    constructorIndex UsageMergedRequirement   {} = 4  -- | Records the imports that we depend on from a home module, -- for recompilation checking.
GHC/Unit/Module/Graph.hs view
@@ -69,6 +69,8 @@    , mgLookupModule    , mgLookupModuleName    , mgHasHoles+   , HomeModuleNameProvidersMap+   , mgHomeModuleNameProvidersMap    , showModMsg      -- ** Reachability queries@@ -158,10 +160,12 @@ import GHC.Utils.Misc ( partitionWith )  import System.FilePath+import Data.Set (Set)+import qualified Data.Set as Set+import Data.Map (Map) import qualified Data.Map as Map import GHC.Types.Unique.DSet-import qualified Data.Set as Set-import Data.Set (Set)+import GHC.Types.Unique.Map (UniqMap, emptyUniqMap, listToUniqMap_C) import GHC.Unit.Module import GHC.Unit.Module.ModNodeKey import GHC.Unit.Module.Stage@@ -206,14 +210,32 @@   -- Cached computation, whether any of the ModuleGraphNode are isHoleModule,   -- This is only used for a hack in GHC.Iface.Load to do with backpack, please   -- remove this at the earliest opportunity.+  , mg_home_module_name_providers_map :: HomeModuleNameProvidersMap+    -- ^ For each module name, which home units provide it.   } +type HomeModuleNameProvidersMap = UniqMap ModuleName (Set UnitId)++mkHomeModuleNameProvidersMap :: [ModuleGraphNode] -> HomeModuleNameProvidersMap+mkHomeModuleNameProvidersMap nodes+    = listToUniqMap_C Set.union $+      [+          (moduleName, Set.singleton unitID) |+              ModuleNode _ moduleNodeInfo <- nodes,+              let moduleName = moduleNodeInfoModuleName moduleNodeInfo,+              let unitID     = moduleNodeInfoUnitId moduleNodeInfo+      ]++mgHomeModuleNameProvidersMap :: ModuleGraph -> HomeModuleNameProvidersMap+mgHomeModuleNameProvidersMap = mg_home_module_name_providers_map+ -- | Why do we ever need to construct empty graphs? Is it because of one shot mode? emptyMG :: ModuleGraph emptyMG = ModuleGraph [] (graphReachability emptyGraph, const Nothing)                          (graphReachability emptyGraph, const Nothing)                          (graphReachability emptyGraph, const Nothing)                          False+                         emptyUniqMap  -- | Construct a module graph. This function should be the only entry point for -- building a 'ModuleGraph', since it is supposed to be built once and never modified.@@ -312,7 +334,7 @@   where     duplicate_errs = rights (Map.elems node_types) -    node_types :: Map.Map NodeKey (Either ModuleNodeType ModuleGraphInvariantError)+    node_types :: Map NodeKey (Either ModuleNodeType ModuleGraphInvariantError)     node_types = Map.fromListWithKey go [ (mkNodeKey n, Left (moduleNodeType n)) | n <- mg_mss ]       where         -- Multiple nodes with the same key are not allowed.@@ -323,7 +345,7 @@  -- | Check that all dependencies in the graph are present in the node_types map. -- This is a helper function used by checkModuleGraph.-checkAllDependenciesInGraph :: Map.Map NodeKey (Either ModuleNodeType ModuleGraphInvariantError)+checkAllDependenciesInGraph :: Map NodeKey (Either ModuleNodeType ModuleGraphInvariantError)                             -> ModuleGraphNode                             -> Maybe ModuleGraphInvariantError checkAllDependenciesInGraph node_types node =@@ -338,7 +360,7 @@ -- | Check if for the fixed module node invariant: -- --   Fixed nodes can only depend on other fixed nodes.-checkFixedModuleInvariant :: Map.Map NodeKey (Either ModuleNodeType ModuleGraphInvariantError)+checkFixedModuleInvariant :: Map NodeKey (Either ModuleNodeType ModuleGraphInvariantError)                 -> ModuleGraphNode                 -> Maybe ModuleGraphInvariantError checkFixedModuleInvariant node_types node = case node of@@ -488,13 +510,17 @@ -- To preserve invariants, 'f' can't change the isBoot status. mapMG :: (ModSummary -> ModSummary) -> ModuleGraph -> ModuleGraph mapMG f mg@ModuleGraph{..} = mg-  { mg_mss = flip fmap mg_mss $ \case-      InstantiationNode uid iuid -> InstantiationNode uid iuid-      LinkNode uid nks -> LinkNode uid nks-      ModuleNode deps (ModuleNodeFixed key loc)  -> ModuleNode deps (ModuleNodeFixed key loc)-      ModuleNode deps (ModuleNodeCompile ms) -> ModuleNode deps (ModuleNodeCompile (f ms))-      UnitNode deps uid -> UnitNode deps uid+  { mg_mss = new_mss+  , mg_home_module_name_providers_map = mkHomeModuleNameProvidersMap new_mss   }+  where+    new_mss =+      flip fmap mg_mss $ \case+        InstantiationNode uid iuid -> InstantiationNode uid iuid+        LinkNode uid nks -> LinkNode uid nks+        ModuleNode deps (ModuleNodeFixed key loc)  -> ModuleNode deps (ModuleNodeFixed key loc)+        ModuleNode deps (ModuleNodeCompile ms) -> ModuleNode deps (ModuleNodeCompile (f ms))+        UnitNode deps uid -> UnitNode deps uid  -- | Map a function 'f' over all the 'ModSummaries', in 'IO'. -- To preserve invariants, 'f' can't change the isBoot status.@@ -567,16 +593,26 @@     allReachableMany td_map (mapMaybe lookup_node nk)  --- | @'mgQueryZero' g root b@ answers the question: can we reach @b@ from @root@+-- | @'mgQueryZero' g root target@ answers the question: can we reach @target@ from @root@ -- in the module graph @g@, only using normal (level 0) imports?+--+-- If the @target@ key is not reachable, there is no path.+-- The @root@ key not being in @g@ results in a panic. mgQueryZero :: ModuleGraph             -> ZeroScopeKey             -> ZeroScopeKey             -> Bool-mgQueryZero mg nka nkb = isReachable td_map na nb where+mgQueryZero mg rootKey targetKey =+  case lookup_node targetKey of+    -- The module we are looking for may not be in the module graph at all,+    -- e.g. if a reference to it did not arise from an explicit import+    -- declaration (as in #26568).+    Nothing -> False+    Just ntarget -> isReachable td_map nroot ntarget+  where+  -- invariant: the root key has to exist in the graph+  nroot = fromJust $ lookup_node rootKey   (td_map, lookup_node) = mg_zero_graph mg-  na = expectJust $ lookup_node nka-  nb = expectJust $ lookup_node nkb   -- | Reachability Query.@@ -847,7 +883,7 @@ -- described in the export list haddocks. -------------------------------------------------------------------------------- -newtype NodeMap a = NodeMap { unNodeMap :: Map.Map NodeKey a }+newtype NodeMap a = NodeMap { unNodeMap :: Map NodeKey a }   deriving (Functor, Traversable, Foldable)  -- | Transitive dependencies, including SOURCE edges@@ -923,7 +959,7 @@     lookup_key :: ZeroScopeKey -> Maybe Int     lookup_key = fmap zeroSummaryNodeKey . lookup_node -    node_map :: Map.Map ZeroScopeKey ZeroSummaryNode+    node_map :: Map ZeroScopeKey ZeroSummaryNode     node_map =       Map.fromList [ (s, node)                    | node <- nodes@@ -1022,7 +1058,7 @@     lookup_key ::  (NodeKey, ModuleStage) -> Maybe Int     lookup_key = fmap stageSummaryNodeKey . lookup_node -    node_map :: Map.Map (NodeKey, ModuleStage) StageSummaryNode+    node_map :: Map (NodeKey, ModuleStage) StageSummaryNode     node_map =       Map.fromList [ (s, node)                    | node <- nodes@@ -1040,10 +1076,13 @@ extendMG :: ModuleGraph -> ModuleGraphNode -> ModuleGraph extendMG ModuleGraph{..} node =   ModuleGraph-    { mg_mss = node : mg_mss-    , mg_graph =  mkTransDeps (node : mg_mss)-    , mg_loop_graph = mkTransLoopDeps (node : mg_mss)-    , mg_zero_graph = mkTransZeroDeps (node : mg_mss)+    { mg_mss = new_mss+    , mg_graph =  mkTransDeps new_mss+    , mg_loop_graph = mkTransLoopDeps new_mss+    , mg_zero_graph = mkTransZeroDeps new_mss     , mg_has_holes = mg_has_holes || maybe False isHsigFile (moduleNodeInfoHscSource =<< mgNodeIsModule node)+    , mg_home_module_name_providers_map = mkHomeModuleNameProvidersMap new_mss     }+  where+    new_mss = node : mg_mss 
GHC/Unit/Module/ModGuts.hs view
@@ -7,7 +7,7 @@  import GHC.Prelude -import GHC.HsToCore.Breakpoints+import GHC.HsToCore.Breakpoints.Types import GHC.ForeignSrcLang  import GHC.Hs
GHC/Unit/Module/ModIface.hs view
@@ -127,6 +127,8 @@ import GHC.Iface.Ext.Fields import GHC.Iface.Recomp.Types +import GHC.HsToCore.Breakpoints.Types+ import GHC.Unit import GHC.Unit.Module.Deps import GHC.Unit.Module.Warnings@@ -425,6 +427,8 @@   -- ^ Extra variable definitions which are **NOT** exposed but when   -- combined with mi_decls allows us to restart code generation.   -- See Note [Interface Files with Core Definitions] and Note [Interface File with Core: Sharing RHSs]+  , mi_sc_modBreaks :: Maybe ModBreaks+  -- ^ If breakpoints are present in @mi_sc_extra_decls@ this field provides this field provides the metadata required by the bytecode debugger.   , mi_sc_foreign :: IfaceForeign   -- ^ Foreign stubs and files to supplement 'mi_extra_decls_'.   -- See Note [Foreign stubs and TH bytecode linking]@@ -754,14 +758,16 @@                    }  instance Binary IfaceSimplifiedCore where-  put_ bh (IfaceSimplifiedCore eds fs) = do+  put_ bh (IfaceSimplifiedCore eds mbs fs) = do     put_ bh eds+    put_ bh mbs     put_ bh fs    get bh = do     eds <- get bh+    mbs <- get bh     fs <- get bh-    return (IfaceSimplifiedCore eds fs)+    return (IfaceSimplifiedCore eds mbs fs)  emptyPartialModIface :: Module -> PartialModIface emptyPartialModIface mod@@ -870,7 +876,7 @@   instance NFData IfaceSimplifiedCore where-  rnf (IfaceSimplifiedCore eds fs) = rnf eds `seq` rnf fs+  rnf (IfaceSimplifiedCore eds mbs fs) = rnf eds `seq` rnf mbs `seq` rnf fs  instance NFData IfaceAbiHashes where   rnf (IfaceAbiHashes a1 a2 a3 a4 a5 a6)@@ -899,13 +905,7 @@     `seq` rnf a14  instance NFData IfaceCache where-  rnf (IfaceCache a1 a2 a3 a4)-    =  rnf a1-    `seq` rnf a2-    `seq` rnf a3-    `seq` rnf a4--+  rnf = rwhnf  forceModIface :: ModIface -> IO () forceModIface iface = () <$ (evaluate $ force iface)
GHC/Unit/Module/WholeCoreBindings.hs view
@@ -9,6 +9,7 @@ import GHC.Driver.DynFlags (DynFlags (targetPlatform), initSDocContext) import GHC.ForeignSrcLang (ForeignSrcLang (..)) import GHC.Iface.Syntax+import GHC.HsToCore.Breakpoints.Types (ModBreaks) import GHC.Prelude import GHC.Types.ForeignStubs import GHC.Unit.Module.Location@@ -127,6 +128,7 @@  data WholeCoreBindings = WholeCoreBindings             { wcb_bindings :: [IfaceBindingX IfaceMaybeRhs IfaceTopBndrInfo] -- ^ serialised tidied core bindings.+            , wcb_modBreaks :: Maybe ModBreaks -- ^ if @wcb_bindings@ contains breakpoints, this field provides the metadata required by the bytecode debugger.             , wcb_module   :: Module  -- ^ The module which the bindings are for             , wcb_mod_location :: ModLocation -- ^ The location where the sources reside.               -- | Stubs for foreign declarations and files added via
GHC/Unit/State.hs view
@@ -5,2272 +5,1249 @@ -- | Unit manipulation module GHC.Unit.State (         module GHC.Unit.Info,--        -- * Reading the package config, and processing cmdline args-        UnitState(..),-        PreloadUnitClosure,-        UnitDatabase (..),-        UnitErr (..),-        emptyUnitState,-        initUnits,-        readUnitDatabases,-        readUnitDatabase,-        getUnitDbRefs,-        resolveUnitDatabase,-        listUnitInfo,--        -- * Querying the package config-        UnitInfoMap,-        lookupUnit,-        lookupUnit',-        unsafeLookupUnit,-        lookupUnitId,-        lookupUnitId',-        unsafeLookupUnitId,--        lookupPackageName,-        resolvePackageImport,-        improveUnit,-        searchPackageId,-        listVisibleModuleNames,-        lookupModuleInAllUnits,-        lookupModuleWithSuggestions,-        lookupModulePackage,-        lookupPluginModuleWithSuggestions,-        requirementMerges,-        LookupResult(..),-        ModuleSuggestion(..),-        ModuleOrigin(..),-        UnusableUnit(..),-        UnusableUnitReason(..),-        pprReason,--        closeUnitDeps,-        closeUnitDeps',-        mayThrowUnitErr,--        -- * Module hole substitution-        ShHoleSubst,-        renameHoleUnit,-        renameHoleModule,-        renameHoleUnit',-        renameHoleModule',-        instUnitToUnit,-        instModuleToModule,--        -- * Pretty-printing-        pprFlag,-        pprUnits,-        pprUnitsSimple,-        pprUnitIdForUser,-        pprUnitInfoForUser,-        pprModuleMap,-        pprWithUnitState,-        pprRawUnitIds,--        -- * Utils-        unwireUnit)-where--import GHC.Prelude--import GHC.Driver.DynFlags--import GHC.Platform-import GHC.Platform.Ways--import GHC.Unit.Database-import GHC.Unit.Info-import GHC.Unit.Ppr-import GHC.Unit.Types-import GHC.Unit.Module-import GHC.Unit.Home--import GHC.Types.Unique.FM-import GHC.Types.Unique.DFM-import GHC.Types.Unique.Set-import GHC.Types.Unique.DSet-import GHC.Types.Unique.Map-import GHC.Types.Unique-import GHC.Types.PkgQual--import GHC.Utils.Misc-import GHC.Utils.Panic-import GHC.Utils.Outputable as Outputable-import GHC.Data.Maybe--import System.Environment ( getEnv )-import GHC.Data.FastString-import qualified GHC.Data.ShortText as ST-import GHC.Utils.Logger-import GHC.Utils.Error-import GHC.Utils.Exception--import System.Directory-import System.FilePath as FilePath-import Control.Monad-import Data.Graph (stronglyConnComp, SCC(..))-import Data.Char ( toUpper )-import Data.List ( intersperse, partition, sortBy, isSuffixOf, sortOn )-import Data.Set (Set)-import Data.Monoid (First(..))-import qualified Data.Semigroup as Semigroup-import qualified Data.Set as Set-import Control.Applicative---- ------------------------------------------------------------------------------ The Unit state---- The unit state is computed by 'initUnits', and kept in HscEnv.--- It is influenced by various command-line flags:------   * @-package \<pkg>@ and @-package-id \<pkg>@ cause @\<pkg>@ to become exposed.---     If @-hide-all-packages@ was not specified, these commands also cause---      all other packages with the same name to become hidden.------   * @-hide-package \<pkg>@ causes @\<pkg>@ to become hidden.------   * (there are a few more flags, check below for their semantics)------ The unit state has the following properties.------   * Let @exposedUnits@ be the set of packages thus exposed.---     Let @depExposedUnits@ be the transitive closure from @exposedUnits@ of---     their dependencies.------   * When searching for a module from a preload import declaration,---     only the exposed modules in @exposedUnits@ are valid.------   * When searching for a module from an implicit import, all modules---     from @depExposedUnits@ are valid.------   * When linking in a compilation manager mode, we link in packages the---     program depends on (the compiler knows this list by the---     time it gets to the link step).  Also, we link in all packages---     which were mentioned with preload @-package@ flags on the command-line,---     or are a transitive dependency of same, or are \"base\"\/\"rts\".---     The reason for this is that we might need packages which don't---     contain any Haskell modules, and therefore won't be discovered---     by the normal mechanism of dependency tracking.---- Notes on DLLs--- ~~~~~~~~~~~~~--- When compiling module A, which imports module B, we need to--- know whether B will be in the same DLL as A.---      If it's in the same DLL, we refer to B_f_closure---      If it isn't, we refer to _imp__B_f_closure--- When compiling A, we record in B's Module value whether it's--- in a different DLL, by setting the DLL flag.---- | Given a module name, there may be multiple ways it came into scope,--- possibly simultaneously.  This data type tracks all the possible ways--- it could have come into scope.  Warning: don't use the record functions,--- they're partial!-data ModuleOrigin =-    -- | Module is hidden, and thus never will be available for import.-    -- (But maybe the user didn't realize), so we'll still keep track-    -- of these modules.)-    ModHidden--    -- | Module is unavailable because the unit is unusable.-  | ModUnusable !UnusableUnit--    -- | Module is public, and could have come from some places.-  | ModOrigin {-        -- | @Just False@ means that this module is in-        -- someone's @exported-modules@ list, but that package is hidden;-        -- @Just True@ means that it is available; @Nothing@ means neither-        -- applies.-        fromOrigUnit :: Maybe Bool-        -- | Is the module available from a reexport of an exposed package?-        -- There could be multiple.-      , fromExposedReexport :: [UnitInfo]-        -- | Is the module available from a reexport of a hidden package?-      , fromHiddenReexport :: [UnitInfo]-        -- | Did the module export come from a package flag? (ToDo: track-        -- more information.-      , fromPackageFlag :: Bool-      }---- | A unusable unit module origin-data UnusableUnit = UnusableUnit-  { uuUnit        :: !Unit               -- ^ Unusable unit-  , uuReason      :: !UnusableUnitReason -- ^ Reason-  , uuIsReexport  :: !Bool               -- ^ Is the "module" a reexport?-  }--instance Outputable ModuleOrigin where-    ppr ModHidden = text "hidden module"-    ppr (ModUnusable _) = text "unusable module"-    ppr (ModOrigin e res rhs f) = sep (punctuate comma (-        (case e of-            Nothing -> []-            Just False -> [text "hidden package"]-            Just True -> [text "exposed package"]) ++-        (if null res-            then []-            else [text "reexport by" <+>-                    sep (map (ppr . mkUnit) res)]) ++-        (if null rhs-            then []-            else [text "hidden reexport by" <+>-                    sep (map (ppr . mkUnit) res)]) ++-        (if f then [text "package flag"] else [])-        ))---- | Smart constructor for a module which is in @exposed-modules@.  Takes--- as an argument whether or not the defining package is exposed.-fromExposedModules :: Bool -> ModuleOrigin-fromExposedModules e = ModOrigin (Just e) [] [] False---- | Smart constructor for a module which is in @reexported-modules@.  Takes--- as an argument whether or not the reexporting package is exposed, and--- also its 'UnitInfo'.-fromReexportedModules :: Bool -> UnitInfo -> ModuleOrigin-fromReexportedModules True pkg = ModOrigin Nothing [pkg] [] False-fromReexportedModules False pkg = ModOrigin Nothing [] [pkg] False---- | Smart constructor for a module which was bound by a package flag.-fromFlag :: ModuleOrigin-fromFlag = ModOrigin Nothing [] [] True--instance Semigroup ModuleOrigin where-    x@(ModOrigin e res rhs f) <> y@(ModOrigin e' res' rhs' f') =-        ModOrigin (g e e') (res ++ res') (rhs ++ rhs') (f || f')-      where g (Just b) (Just b')-                | b == b'   = Just b-                | otherwise = pprPanic "ModOrigin: package both exposed/hidden" $-                    text "x: " <> ppr x $$ text "y: " <> ppr y-            g Nothing x = x-            g x Nothing = x--    x <> y = pprPanic "ModOrigin: module origin mismatch" $-                 text "x: " <> ppr x $$ text "y: " <> ppr y--instance Monoid ModuleOrigin where-    mempty = ModOrigin Nothing [] [] False-    mappend = (Semigroup.<>)---- | Is the name from the import actually visible? (i.e. does it cause--- ambiguity, or is it only relevant when we're making suggestions?)-originVisible :: ModuleOrigin -> Bool-originVisible ModHidden = False-originVisible (ModUnusable _) = False-originVisible (ModOrigin b res _ f) = b == Just True || not (null res) || f---- | Are there actually no providers for this module?  This will never occur--- except when we're filtering based on package imports.-originEmpty :: ModuleOrigin -> Bool-originEmpty (ModOrigin Nothing [] [] False) = True-originEmpty _ = False--type PreloadUnitClosure = UniqSet UnitId---- | 'UniqFM' map from 'Unit' to a 'UnitVisibility'.-type VisibilityMap = UniqMap Unit UnitVisibility---- | 'UnitVisibility' records the various aspects of visibility of a particular--- 'Unit'.-data UnitVisibility = UnitVisibility-    { uv_expose_all :: Bool-      --  ^ Should all modules in exposed-modules should be dumped into scope?-    , uv_renamings :: [(ModuleName, ModuleName)]-      -- ^ Any custom renamings that should bring extra 'ModuleName's into-      -- scope.-    , uv_package_name :: First FastString-      -- ^ The package name associated with the 'Unit'.  This is used-      -- to implement legacy behavior where @-package foo-0.1@ implicitly-      -- hides any packages named @foo@-    , uv_requirements :: UniqMap ModuleName (Set InstantiatedModule)-      -- ^ The signatures which are contributed to the requirements context-      -- from this unit ID.-    , uv_explicit :: Maybe PackageArg-      -- ^ Whether or not this unit was explicitly brought into scope,-      -- as opposed to implicitly via the 'exposed' fields in the-      -- package database (when @-hide-all-packages@ is not passed.)-    }--instance Outputable UnitVisibility where-    ppr (UnitVisibility {-        uv_expose_all = b,-        uv_renamings = rns,-        uv_package_name = First mb_pn,-        uv_requirements = reqs,-        uv_explicit = explicit-    }) = ppr (b, rns, mb_pn, reqs, explicit)--instance Semigroup UnitVisibility where-    uv1 <> uv2-        = UnitVisibility-          { uv_expose_all = uv_expose_all uv1 || uv_expose_all uv2-          , uv_renamings = uv_renamings uv1 ++ uv_renamings uv2-          , uv_package_name = mappend (uv_package_name uv1) (uv_package_name uv2)-          , uv_requirements = plusUniqMap_C Set.union (uv_requirements uv2) (uv_requirements uv1)-          , uv_explicit = uv_explicit uv1 <|> uv_explicit uv2-          }--instance Monoid UnitVisibility where-    mempty = UnitVisibility-             { uv_expose_all = False-             , uv_renamings = []-             , uv_package_name = First Nothing-             , uv_requirements = emptyUniqMap-             , uv_explicit = Nothing-             }-    mappend = (Semigroup.<>)----- | Unit configuration-data UnitConfig = UnitConfig-   { unitConfigPlatformArchOS :: !ArchOS        -- ^ Platform arch and OS-   , unitConfigWays           :: !Ways          -- ^ Ways to use--   , unitConfigAllowVirtual   :: !Bool          -- ^ Allow virtual units-      -- ^ Do we allow the use of virtual units instantiated on-the-fly (see-      -- Note [About units] in GHC.Unit). This should only be true when we are-      -- type-checking an indefinite unit (not producing any code).--   , unitConfigProgramName    :: !String-      -- ^ Name of the compiler (e.g. "GHC", "GHCJS"). Used to fetch environment-      -- variables such as "GHC[JS]_PACKAGE_PATH".--   , unitConfigGlobalDB :: !FilePath    -- ^ Path to global DB-   , unitConfigGHCDir   :: !FilePath    -- ^ Main GHC dir: contains settings, etc.-   , unitConfigDBName   :: !String      -- ^ User DB name (e.g. "package.conf.d")--   , unitConfigAutoLink       :: ![UnitId] -- ^ Units to link automatically (e.g. base, rts)-   , unitConfigDistrustAll    :: !Bool     -- ^ Distrust all units by default-   , unitConfigHideAll        :: !Bool     -- ^ Hide all units by default-   , unitConfigHideAllPlugins :: !Bool     -- ^ Hide all plugins units by default--   , unitConfigDBCache      :: Maybe [UnitDatabase UnitId]-      -- ^ Cache of databases to use, in the order they were specified on the-      -- command line (later databases shadow earlier ones).-      -- If Nothing, databases will be found using `unitConfigFlagsDB`.--   -- command-line flags-   , unitConfigFlagsDB      :: [PackageDBFlag]     -- ^ Unit databases flags-   , unitConfigFlagsExposed :: [PackageFlag]       -- ^ Exposed units-   , unitConfigFlagsIgnored :: [IgnorePackageFlag] -- ^ Ignored units-   , unitConfigFlagsTrusted :: [TrustFlag]         -- ^ Trusted units-   , unitConfigFlagsPlugins :: [PackageFlag]       -- ^ Plugins exposed units-   , unitConfigHomeUnits    :: Set.Set UnitId-   }--initUnitConfig :: DynFlags -> Maybe [UnitDatabase UnitId] -> Set.Set UnitId -> UnitConfig-initUnitConfig dflags cached_dbs home_units =-   let !hu_id             = homeUnitId_ dflags-       !hu_instanceof     = homeUnitInstanceOf_ dflags-       !hu_instantiations = homeUnitInstantiations_ dflags--       autoLink-         | not (gopt Opt_AutoLinkPackages dflags) = []-         -- By default we add base, ghc-internal and rts to the preload units (when they are-         -- found in the unit database) except when we are building them-         ---         -- Since "base" is not wired in, then the unit-id is discovered-         -- from the settings file by default, but can be overriden by power-users-         -- by specifying `-base-unit-id` flag.-         | otherwise = filter (hu_id /=) [baseUnitId dflags, ghcInternalUnitId, rtsUnitId]--       -- if the home unit is indefinite, it means we are type-checking it only-       -- (not producing any code). Hence we can use virtual units instantiated-       -- on-the-fly. See Note [About units] in GHC.Unit-       allow_virtual_units = case (hu_instanceof, hu_instantiations) of-            (Just u, is) -> u == hu_id && any (isHoleModule . snd) is-            _            -> False--   in UnitConfig-      { unitConfigPlatformArchOS = platformArchOS (targetPlatform dflags)-      , unitConfigProgramName    = programName dflags-      , unitConfigWays           = ways dflags-      , unitConfigAllowVirtual   = allow_virtual_units--      , unitConfigGlobalDB       = globalPackageDatabasePath dflags-      , unitConfigGHCDir         = topDir dflags-      , unitConfigDBName         = "package.conf.d"--      , unitConfigAutoLink       = autoLink-      , unitConfigDistrustAll    = gopt Opt_DistrustAllPackages dflags-      , unitConfigHideAll        = gopt Opt_HideAllPackages dflags-      , unitConfigHideAllPlugins = gopt Opt_HideAllPluginPackages dflags--      , unitConfigDBCache      = cached_dbs-      , unitConfigFlagsDB      = map (offsetPackageDb (workingDirectory dflags)) $ packageDBFlags dflags-      , unitConfigFlagsExposed = packageFlags dflags-      , unitConfigFlagsIgnored = ignorePackageFlags dflags-      , unitConfigFlagsTrusted = trustFlags dflags-      , unitConfigFlagsPlugins = pluginPackageFlags dflags-      , unitConfigHomeUnits    = home_units--      }--  where-    offsetPackageDb :: Maybe FilePath -> PackageDBFlag -> PackageDBFlag-    offsetPackageDb (Just offset) (PackageDB (PkgDbPath p)) | isRelative p = PackageDB (PkgDbPath (offset </> p))-    offsetPackageDb _ p = p----- | Map from 'ModuleName' to a set of module providers (i.e. a 'Module' and--- its 'ModuleOrigin').------ NB: the set is in fact a 'Map Module ModuleOrigin', probably to keep only one--- origin for a given 'Module'--type ModuleNameProvidersMap =-    UniqMap ModuleName (UniqMap Module ModuleOrigin)--data UnitState = UnitState {-  -- | A mapping of 'Unit' to 'UnitInfo'.  This list is adjusted-  -- so that only valid units are here.  'UnitInfo' reflects-  -- what was stored *on disk*, except for the 'trusted' flag, which-  -- is adjusted at runtime.  (In particular, some units in this map-  -- may have the 'exposed' flag be 'False'.)-  unitInfoMap :: UnitInfoMap,--  -- | The set of transitively reachable units according-  -- to the explicitly provided command line arguments.-  -- A fully instantiated VirtUnit may only be replaced by a RealUnit from-  -- this set.-  -- See Note [VirtUnit to RealUnit improvement]-  preloadClosure :: PreloadUnitClosure,--  -- | A mapping of 'PackageName' to 'UnitId'. If several units have the same-  -- package name (e.g. different instantiations), then we return one of them...-  -- This is used when users refer to packages in Backpack includes.-  -- And also to resolve package qualifiers with the PackageImports extension.-  packageNameMap            :: UniqFM PackageName UnitId,--  -- | A mapping from database unit keys to wired in unit ids.-  wireMap :: UniqMap UnitId UnitId,--  -- | A mapping from wired in unit ids to unit keys from the database.-  unwireMap :: UniqMap UnitId UnitId,--  -- | The units we're going to link in eagerly.  This list-  -- should be in reverse dependency order; that is, a unit-  -- is always mentioned before the units it depends on.-  preloadUnits      :: [UnitId],--  -- | Units which we explicitly depend on (from a command line flag).-  -- We'll use this to generate version macros and the unused packages warning. The-  -- original flag which was used to bring the unit into scope is recorded for the-  -- -Wunused-packages warning.-  explicitUnits :: [(Unit, Maybe PackageArg)],--  homeUnitDepends    :: [UnitId],--  -- | This is a full map from 'ModuleName' to all modules which may possibly-  -- be providing it.  These providers may be hidden (but we'll still want-  -- to report them in error messages), or it may be an ambiguous import.-  moduleNameProvidersMap    :: !ModuleNameProvidersMap,--  -- | A map, like 'moduleNameProvidersMap', but controlling plugin visibility.-  pluginModuleNameProvidersMap    :: !ModuleNameProvidersMap,--  -- | A map saying, for each requirement, what interfaces must be merged-  -- together when we use them.  For example, if our dependencies-  -- are @p[A=\<A>]@ and @q[A=\<A>,B=r[C=\<A>]:B]@, then the interfaces-  -- to merge for A are @p[A=\<A>]:A@, @q[A=\<A>,B=r[C=\<A>]:B]:A@-  -- and @r[C=\<A>]:C@.-  ---  -- There's an entry in this map for each hole in our home library.-  requirementContext :: UniqMap ModuleName [InstantiatedModule],--  -- | Indicate if we can instantiate units on-the-fly.-  ---  -- This should only be true when we are type-checking an indefinite unit.-  -- See Note [About units] in GHC.Unit.-  allowVirtualUnits :: !Bool-  }--emptyUnitState :: UnitState-emptyUnitState = UnitState {-    unitInfoMap    = emptyUniqMap,-    preloadClosure = emptyUniqSet,-    packageNameMap = emptyUFM,-    wireMap        = emptyUniqMap,-    unwireMap      = emptyUniqMap,-    preloadUnits   = [],-    explicitUnits  = [],-    homeUnitDepends = [],-    moduleNameProvidersMap       = emptyUniqMap,-    pluginModuleNameProvidersMap = emptyUniqMap,-    requirementContext           = emptyUniqMap,-    allowVirtualUnits = False-    }---- | Unit database-data UnitDatabase unit = UnitDatabase-   { unitDatabasePath  :: FilePath-   , unitDatabaseUnits :: [GenUnitInfo unit]-   }--instance Outputable u => Outputable (UnitDatabase u) where-  ppr (UnitDatabase fp _u) = text "DB:" <+> text fp--type UnitInfoMap = UniqMap UnitId UnitInfo---- | Find the unit we know about with the given unit, if any-lookupUnit :: UnitState -> Unit -> Maybe UnitInfo-lookupUnit pkgs = lookupUnit' (allowVirtualUnits pkgs) (unitInfoMap pkgs) (preloadClosure pkgs)---- | A more specialized interface, which doesn't require a 'UnitState' (so it--- can be used while we're initializing 'DynFlags')------ Parameters:---    * a boolean specifying whether or not to look for on-the-fly renamed interfaces---    * a 'UnitInfoMap'---    * a 'PreloadUnitClosure'-lookupUnit' :: Bool -> UnitInfoMap -> PreloadUnitClosure -> Unit -> Maybe UnitInfo-lookupUnit' allowOnTheFlyInst pkg_map closure u = case u of-   HoleUnit   -> error "Hole unit"-   RealUnit i -> lookupUniqMap pkg_map (unDefinite i)-   VirtUnit i-      | allowOnTheFlyInst-      -> -- lookup UnitInfo of the indefinite unit to be instantiated and-         -- instantiate it on-the-fly-         fmap (renameUnitInfo pkg_map closure (instUnitInsts i))-           (lookupUniqMap pkg_map (instUnitInstanceOf i))--      | otherwise-      -> -- lookup UnitInfo by virtual UnitId. This is used to find indefinite-         -- units. Even if they are real, installed units, they can't use the-         -- `RealUnit` constructor (it is reserved for definite units) so we use-         -- the `VirtUnit` constructor.-         lookupUniqMap pkg_map (virtualUnitId i)---- | Find the unit we know about with the given unit id, if any-lookupUnitId :: UnitState -> UnitId -> Maybe UnitInfo-lookupUnitId state uid = lookupUnitId' (unitInfoMap state) uid---- | Find the unit we know about with the given unit id, if any-lookupUnitId' :: UnitInfoMap -> UnitId -> Maybe UnitInfo-lookupUnitId' db uid = lookupUniqMap db uid----- | Looks up the given unit in the unit state, panicking if it is not found-unsafeLookupUnit :: HasDebugCallStack => UnitState -> Unit -> UnitInfo-unsafeLookupUnit state u = case lookupUnit state u of-   Just info -> info-   Nothing   -> pprPanic "unsafeLookupUnit" (ppr u)---- | Looks up the given unit id in the unit state, panicking if it is not found-unsafeLookupUnitId :: HasDebugCallStack => UnitState -> UnitId -> UnitInfo-unsafeLookupUnitId state uid = case lookupUnitId state uid of-   Just info -> info-   Nothing   -> pprPanic "unsafeLookupUnitId" (ppr uid)----- | Find the unit we know about with the given package name (e.g. @foo@), if any--- (NB: there might be a locally defined unit name which overrides this)--- This function is unsafe to use in general because it doesn't respect package--- visibility.-lookupPackageName :: UnitState -> PackageName -> Maybe UnitId-lookupPackageName pkgstate n = lookupUFM (packageNameMap pkgstate) n---- | Search for units with a given package ID (e.g. \"foo-0.1\")-searchPackageId :: UnitState -> PackageId -> [UnitInfo]-searchPackageId pkgstate pid = filter ((pid ==) . unitPackageId)-                               (listUnitInfo pkgstate)---- | Find the UnitId which an import qualified by a package import comes from.--- Compared to 'lookupPackageName', this function correctly accounts for visibility,--- renaming and thinning.-resolvePackageImport :: UnitState -> ModuleName -> PackageName -> Maybe UnitId-resolvePackageImport unit_st mn pn = do-  -- 1. Find all modules providing the ModuleName (this accounts for visibility/thinning etc)-  providers <- filterUniqMap originVisible <$> lookupUniqMap (moduleNameProvidersMap unit_st) mn-  -- 2. Get the UnitIds of the candidates-  let candidates_uid = concatMap to_uid $ sortOn fst $ nonDetUniqMapToList providers-  -- 3. Get the package names of the candidates-  let candidates_units = map (\ui -> ((unitPackageName ui), unitId ui))-                              $ mapMaybe (\uid -> lookupUniqMap (unitInfoMap unit_st) uid) candidates_uid-  -- 4. Check to see if the PackageName helps us disambiguate any candidates.-  lookup pn candidates_units--  where--    -- Get the UnitId from which a visible identifier is from-    to_uid :: (Module, ModuleOrigin) -> [UnitId]-    to_uid (mod, ModOrigin mo re_exps _ _) =-      case mo of-        -- Available directly, but also potentially from re-exports-        Just True ->  (toUnitId (moduleUnit mod)) : map unitId re_exps-        -- Just available from these re-exports-        _ -> map unitId re_exps-    to_uid _ = []---- | Create a Map UnitId UnitInfo------ For each instantiated unit, we add two map keys:---    * the real unit id---    * the virtual unit id made from its instantiation------ We do the same thing for fully indefinite units (which are "instantiated"--- with module holes).----mkUnitInfoMap :: [UnitInfo] -> UnitInfoMap-mkUnitInfoMap infos = foldl' add emptyUniqMap infos-  where-   mkVirt      p = virtualUnitId (mkInstantiatedUnit (unitInstanceOf p) (unitInstantiations p))-   add pkg_map p-      | not (null (unitInstantiations p))-      = addToUniqMap (addToUniqMap pkg_map (mkVirt p) p)-                     (unitId p) p-      | otherwise-      = addToUniqMap pkg_map (unitId p) p---- | Get a list of entries from the unit database.  NB: be careful with--- this function, although all units in this map are "visible", this--- does not imply that the exposed-modules of the unit are available--- (they may have been thinned or renamed).-listUnitInfo :: UnitState -> [UnitInfo]-listUnitInfo state = nonDetEltsUniqMap (unitInfoMap state)---- ------------------------------------------------------------------------------- Loading the unit db files and building up the unit state---- | Read the unit database files, and sets up various internal tables of--- unit information, according to the unit-related flags on the--- command-line (@-package@, @-hide-package@ etc.)------ 'initUnits' can be called again subsequently after updating the--- 'packageFlags' field of the 'DynFlags', and it will update the--- 'unitState' in 'DynFlags'.-initUnits :: Logger -> DynFlags -> Maybe [UnitDatabase UnitId] -> Set.Set UnitId -> IO ([UnitDatabase UnitId], UnitState, HomeUnit, Maybe PlatformConstants)-initUnits logger dflags cached_dbs home_units = do--  let forceUnitInfoMap (state, _) = unitInfoMap state `seq` ()--  (unit_state,dbs) <- withTiming logger (text "initializing unit database")-                   forceUnitInfoMap-                 $ mkUnitState logger (initUnitConfig dflags cached_dbs home_units)--  putDumpFileMaybe logger Opt_D_dump_mod_map "Module Map"-    FormatText (updSDocContext (\ctx -> ctx {sdocLineLength = 200})-                $ pprModuleMap (moduleNameProvidersMap unit_state))--  let home_unit = mkHomeUnit unit_state-                             (homeUnitId_ dflags)-                             (homeUnitInstanceOf_ dflags)-                             (homeUnitInstantiations_ dflags)--  -- Try to find platform constants-  ---  -- See Note [Platform constants] in GHC.Platform-  mconstants <- if homeUnitId_ dflags == rtsUnitId-    then do-      -- we're building the RTS! Lookup DerivedConstants.h in the include paths-      lookupPlatformConstants (includePathsGlobal (includePaths dflags))-    else-      -- lookup the DerivedConstants.h header bundled with the RTS unit. We-      -- don't fail if we can't find the RTS unit as it can be a valid (but-      -- uncommon) case, e.g. building a C utility program (not depending on the-      -- RTS) before building the RTS. In any case, we will fail later on if we-      -- really need to use the platform constants but they have not been loaded.-      case lookupUnitId unit_state rtsUnitId of-        Nothing   -> return Nothing-        Just info -> lookupPlatformConstants (fmap ST.unpack (unitIncludeDirs info))--  return (dbs,unit_state,home_unit,mconstants)--mkHomeUnit-    :: UnitState-    -> UnitId                 -- ^ Home unit id-    -> Maybe UnitId           -- ^ Home unit instance of-    -> [(ModuleName, Module)] -- ^ Home unit instantiations-    -> HomeUnit-mkHomeUnit unit_state hu_id hu_instanceof hu_instantiations_ =-    let-        -- Some wired units can be used to instantiate the home unit. We need to-        -- replace their unit keys with their wired unit ids.-        wmap              = wireMap unit_state-        hu_instantiations = map (fmap (upd_wired_in_mod wmap)) hu_instantiations_-    in case (hu_instanceof, hu_instantiations) of-      (Nothing,[]) -> DefiniteHomeUnit hu_id Nothing-      (Nothing, _) -> throwGhcException $ CmdLineError ("Use of -instantiated-with requires -this-component-id")-      (Just _, []) -> throwGhcException $ CmdLineError ("Use of -this-component-id requires -instantiated-with")-      (Just u, is)-         -- detect fully indefinite units: all their instantiations are hole-         -- modules and the home unit id is the same as the instantiating unit-         -- id (see Note [About units] in GHC.Unit)-         | all (isHoleModule . snd) is && u == hu_id-         -> IndefiniteHomeUnit u is-         -- otherwise it must be that we (fully) instantiate an indefinite unit-         -- to make it definite.-         -- TODO: error when the unit is partially instantiated??-         | otherwise-         -> DefiniteHomeUnit hu_id (Just (u, is))---- -------------------------------------------------------------------------------- Reading the unit database(s)--readUnitDatabases :: Logger -> UnitConfig -> IO [UnitDatabase UnitId]-readUnitDatabases logger cfg = do-  conf_refs <- getUnitDbRefs cfg-  confs     <- liftM catMaybes $ mapM (resolveUnitDatabase cfg) conf_refs-  mapM (readUnitDatabase logger cfg) confs---getUnitDbRefs :: UnitConfig -> IO [PkgDbRef]-getUnitDbRefs cfg = do-  let system_conf_refs = [UserPkgDb, GlobalPkgDb]--  e_pkg_path <- tryIO (getEnv $ map toUpper (unitConfigProgramName cfg) ++ "_PACKAGE_PATH")-  let base_conf_refs = case e_pkg_path of-        Left _ -> system_conf_refs-        Right path-         | Just (xs, x) <- snocView path, isSearchPathSeparator x-         -> map PkgDbPath (splitSearchPath xs) ++ system_conf_refs-         | otherwise-         -> map PkgDbPath (splitSearchPath path)--  -- Apply the package DB-related flags from the command line to get the-  -- final list of package DBs.-  ---  -- Notes on ordering:-  --  * The list of flags is reversed (later ones first)-  --  * We work with the package DB list in "left shadows right" order-  --  * and finally reverse it at the end, to get "right shadows left"-  ---  return $ reverse (foldr doFlag base_conf_refs (unitConfigFlagsDB cfg))- where-  doFlag (PackageDB p) dbs = p : dbs-  doFlag NoUserPackageDB dbs = filter isNotUser dbs-  doFlag NoGlobalPackageDB dbs = filter isNotGlobal dbs-  doFlag ClearPackageDBs _ = []--  isNotUser UserPkgDb = False-  isNotUser _ = True--  isNotGlobal GlobalPkgDb = False-  isNotGlobal _ = True---- | Return the path of a package database from a 'PkgDbRef'. Return 'Nothing'--- when the user database filepath is expected but the latter doesn't exist.------ NB: This logic is reimplemented in Cabal, so if you change it,--- make sure you update Cabal. (Or, better yet, dump it in the--- compiler info so Cabal can use the info.)-resolveUnitDatabase :: UnitConfig -> PkgDbRef -> IO (Maybe FilePath)-resolveUnitDatabase cfg GlobalPkgDb = return $ Just (unitConfigGlobalDB cfg)-resolveUnitDatabase cfg UserPkgDb = runMaybeT $ do-  dir <- versionedAppDir (unitConfigProgramName cfg) (unitConfigPlatformArchOS cfg)-  let pkgconf = dir </> unitConfigDBName cfg-  exist <- tryMaybeT $ doesDirectoryExist pkgconf-  if exist then return pkgconf else mzero-resolveUnitDatabase _ (PkgDbPath name) = return $ Just name--readUnitDatabase :: Logger -> UnitConfig -> FilePath -> IO (UnitDatabase UnitId)-readUnitDatabase logger cfg conf_file = do-  isdir <- doesDirectoryExist conf_file--  proto_pkg_configs <--    if isdir-       then readDirStyleUnitInfo conf_file-       else do-            isfile <- doesFileExist conf_file-            if isfile-               then do-                 mpkgs <- tryReadOldFileStyleUnitInfo-                 case mpkgs of-                   Just pkgs -> return pkgs-                   Nothing   -> throwGhcExceptionIO $ InstallationError $-                      "ghc no longer supports single-file style package " ++-                      "databases (" ++ conf_file ++-                      ") use 'ghc-pkg init' to create the database with " ++-                      "the correct format."-               else throwGhcExceptionIO $ InstallationError $-                      "can't find a package database at " ++ conf_file--  let-      -- Fix #16360: remove trailing slash from conf_file before calculating pkgroot-      conf_file' = dropTrailingPathSeparator conf_file-      top_dir = unitConfigGHCDir cfg-      pkgroot = takeDirectory conf_file'-      pkg_configs1 = map (mungeUnitInfo top_dir pkgroot . mapUnitInfo (\(UnitKey x) -> UnitId x) . mkUnitKeyInfo)-                         proto_pkg_configs-  ---  return $ UnitDatabase conf_file' pkg_configs1-  where-    readDirStyleUnitInfo conf_dir = do-      let filename = conf_dir </> "package.cache"-      cache_exists <- doesFileExist filename-      if cache_exists-        then do-          debugTraceMsg logger 2 $ text "Using binary package database:" <+> text filename-          readPackageDbForGhc filename-        else do-          -- If there is no package.cache file, we check if the database is not-          -- empty by inspecting if the directory contains any .conf file. If it-          -- does, something is wrong and we fail. Otherwise we assume that the-          -- database is empty.-          debugTraceMsg logger 2 $ text "There is no package.cache in"-                      <+> text conf_dir-                       <> text ", checking if the database is empty"-          db_empty <- all (not . isSuffixOf ".conf")-                   <$> getDirectoryContents conf_dir-          if db_empty-            then do-              debugTraceMsg logger 3 $ text "There are no .conf files in"-                          <+> text conf_dir <> text ", treating"-                          <+> text "package database as empty"-              return []-            else-              throwGhcExceptionIO $ InstallationError $-                "there is no package.cache in " ++ conf_dir ++-                " even though package database is not empty"---    -- Single-file style package dbs have been deprecated for some time, but-    -- it turns out that Cabal was using them in one place. So this is a-    -- workaround to allow older Cabal versions to use this newer ghc.-    -- We check if the file db contains just "[]" and if so, we look for a new-    -- dir-style db in conf_file.d/, ie in a dir next to the given file.-    -- We cannot just replace the file with a new dir style since Cabal still-    -- assumes it's a file and tries to overwrite with 'writeFile'.-    -- ghc-pkg also cooperates with this workaround.-    tryReadOldFileStyleUnitInfo = do-      content <- readFile conf_file `catchIO` \_ -> return ""-      if take 2 content == "[]"-        then do-          let conf_dir = conf_file <.> "d"-          direxists <- doesDirectoryExist conf_dir-          if direxists-             then do debugTraceMsg logger 2 (text "Ignoring old file-style db and trying:" <+> text conf_dir)-                     liftM Just (readDirStyleUnitInfo conf_dir)-             else return (Just []) -- ghc-pkg will create it when it's updated-        else return Nothing--distrustAllUnits :: [UnitInfo] -> [UnitInfo]-distrustAllUnits pkgs = map distrust pkgs-  where-    distrust pkg = pkg{ unitIsTrusted = False }--mungeUnitInfo :: FilePath -> FilePath-                   -> UnitInfo -> UnitInfo-mungeUnitInfo top_dir pkgroot =-    mungeDynLibFields-  . mungeUnitInfoPaths (ST.pack top_dir) (ST.pack pkgroot)--mungeDynLibFields :: UnitInfo -> UnitInfo-mungeDynLibFields pkg =-    pkg {-      unitLibraryDynDirs = case unitLibraryDynDirs pkg of-         [] -> unitLibraryDirs pkg-         ds -> ds-    }---- -------------------------------------------------------------------------------- Modify our copy of the unit database based on trust flags,--- -trust and -distrust.--applyTrustFlag-   :: UnitPrecedenceMap-   -> UnusableUnits-   -> [UnitInfo]-   -> TrustFlag-   -> MaybeErr UnitErr [UnitInfo]-applyTrustFlag prec_map unusable pkgs flag =-  case flag of-    -- we trust all matching packages. Maybe should only trust first one?-    -- and leave others the same or set them untrusted-    TrustPackage str ->-       case selectPackages prec_map (PackageArg str) pkgs unusable of-         Left ps       -> Failed (TrustFlagErr flag ps)-         Right (ps,qs) -> Succeeded (map trust ps ++ qs)-          where trust p = p {unitIsTrusted=True}--    DistrustPackage str ->-       case selectPackages prec_map (PackageArg str) pkgs unusable of-         Left ps       -> Failed (TrustFlagErr flag ps)-         Right (ps,qs) -> Succeeded (distrustAllUnits ps ++ qs)--applyPackageFlag-   :: UnitPrecedenceMap-   -> UnitInfoMap-   -> PreloadUnitClosure-   -> UnusableUnits-   -> Bool -- if False, if you expose a package, it implicitly hides-           -- any previously exposed packages with the same name-   -> [UnitInfo]-   -> VisibilityMap           -- Initially exposed-   -> PackageFlag             -- flag to apply-   -> MaybeErr UnitErr VisibilityMap -- Now exposed--applyPackageFlag prec_map pkg_map closure unusable no_hide_others pkgs vm flag =-  case flag of-    ExposePackage _ arg (ModRenaming b rns) ->-       case findPackages prec_map pkg_map closure arg pkgs unusable of-         Left ps     -> Failed (PackageFlagErr flag ps)-         Right (p:_) -> Succeeded vm'-          where-           n = fsPackageName p--           -- If a user says @-unit-id p[A=<A>]@, this imposes-           -- a requirement on us: whatever our signature A is,-           -- it must fulfill all of p[A=<A>]:A's requirements.-           -- This method is responsible for computing what our-           -- inherited requirements are.-           reqs | UnitIdArg orig_uid <- arg = collectHoles orig_uid-                | otherwise                 = emptyUniqMap--           collectHoles uid = case uid of-             HoleUnit       -> emptyUniqMap-             RealUnit {}    -> emptyUniqMap -- definite units don't have holes-             VirtUnit indef ->-                  let local = [ unitUniqMap-                                  (moduleName mod)-                                  (Set.singleton $ Module indef mod_name)-                              | (mod_name, mod) <- instUnitInsts indef-                              , isHoleModule mod ]-                      recurse = [ collectHoles (moduleUnit mod)-                                | (_, mod) <- instUnitInsts indef ]-                  in plusUniqMapListWith Set.union $ local ++ recurse--           uv = UnitVisibility-                { uv_expose_all = b-                , uv_renamings = rns-                , uv_package_name = First (Just n)-                , uv_requirements = reqs-                , uv_explicit = Just arg-                }-           vm' = addToUniqMap_C mappend vm_cleared (mkUnit p) uv-           -- In the old days, if you said `ghc -package p-0.1 -package p-0.2`-           -- (or if p-0.1 was registered in the pkgdb as exposed: True),-           -- the second package flag would override the first one and you-           -- would only see p-0.2 in exposed modules.  This is good for-           -- usability.-           ---           -- However, with thinning and renaming (or Backpack), there might be-           -- situations where you legitimately want to see two versions of a-           -- package at the same time, and this behavior would make it-           -- impossible to do so.  So we decided that if you pass-           -- -hide-all-packages, this should turn OFF the overriding behavior-           -- where an exposed package hides all other packages with the same-           -- name.  This should not affect Cabal at all, which only ever-           -- exposes one package at a time.-           ---           -- NB: Why a variable no_hide_others?  We have to apply this logic to-           -- -plugin-package too, and it's more consistent if the switch in-           -- behavior is based off of-           -- -hide-all-packages/-hide-all-plugin-packages depending on what-           -- flag is in question.-           vm_cleared | no_hide_others = vm-                      -- NB: renamings never clear-                      | (_:_) <- rns = vm-                      | otherwise = filterWithKeyUniqMap-                            (\k uv -> k == mkUnit p-                                   || First (Just n) /= uv_package_name uv) vm-         _ -> panic "applyPackageFlag"--    HidePackage str ->-       case findPackages prec_map pkg_map closure (PackageArg str) pkgs unusable of-         Left ps  -> Failed (PackageFlagErr flag ps)-         Right ps -> Succeeded $ foldl' delFromUniqMap vm (map mkUnit ps)---- | Like 'selectPackages', but doesn't return a list of unmatched--- packages.  Furthermore, any packages it returns are *renamed*--- if the 'UnitArg' has a renaming associated with it.-findPackages :: UnitPrecedenceMap-             -> UnitInfoMap-             -> PreloadUnitClosure-             -> PackageArg -> [UnitInfo]-             -> UnusableUnits-             -> Either [(UnitInfo, UnusableUnitReason)]-                [UnitInfo]-findPackages prec_map pkg_map closure arg pkgs unusable-  = let ps = mapMaybe (finder arg) pkgs-    in if null ps-        then Left (mapMaybe (\(x,y) -> finder arg x >>= \x' -> return (x',y))-                            (nonDetEltsUniqMap unusable))-        else Right (sortByPreference prec_map ps)-  where-    finder (PackageArg str) p-      = if matchingStr str p-          then Just p-          else Nothing-    finder (UnitIdArg uid) p-      = case uid of-          RealUnit (Definite iuid)-            | iuid == unitId p-            -> Just p-          VirtUnit inst-            | instUnitInstanceOf inst == unitId p-            -> Just (renameUnitInfo pkg_map closure (instUnitInsts inst) p)-          _ -> Nothing--selectPackages :: UnitPrecedenceMap -> PackageArg -> [UnitInfo]-               -> UnusableUnits-               -> Either [(UnitInfo, UnusableUnitReason)]-                  ([UnitInfo], [UnitInfo])-selectPackages prec_map arg pkgs unusable-  = let matches = matching arg-        (ps,rest) = partition matches pkgs-    in if null ps-        then Left (filter (matches.fst) (nonDetEltsUniqMap unusable))-        else Right (sortByPreference prec_map ps, rest)---- | Rename a 'UnitInfo' according to some module instantiation.-renameUnitInfo :: UnitInfoMap -> PreloadUnitClosure -> [(ModuleName, Module)] -> UnitInfo -> UnitInfo-renameUnitInfo pkg_map closure insts conf =-    let hsubst = listToUFM insts-        smod  = renameHoleModule' pkg_map closure hsubst-        new_insts = map (\(k,v) -> (k,smod v)) (unitInstantiations conf)-    in conf {-        unitInstantiations = new_insts,-        unitExposedModules = map (\(mod_name, mb_mod) -> (mod_name, fmap smod mb_mod))-                             (unitExposedModules conf)-    }----- A package named on the command line can either include the--- version, or just the name if it is unambiguous.-matchingStr :: String -> UnitInfo -> Bool-matchingStr str p-        =  str == unitPackageIdString p-        || str == unitPackageNameString p--matchingId :: UnitId -> UnitInfo -> Bool-matchingId uid p = uid == unitId p--matching :: PackageArg -> UnitInfo -> Bool-matching (PackageArg str) = matchingStr str-matching (UnitIdArg (RealUnit (Definite uid))) = matchingId uid-matching (UnitIdArg _)  = \_ -> False -- TODO: warn in this case---- | This sorts a list of packages, putting "preferred" packages first.--- See 'compareByPreference' for the semantics of "preference".-sortByPreference :: UnitPrecedenceMap -> [UnitInfo] -> [UnitInfo]-sortByPreference prec_map = sortBy (flip (compareByPreference prec_map))---- | Returns 'GT' if @pkg@ should be preferred over @pkg'@ when picking--- which should be "active".  Here is the order of preference:------      1. First, prefer the latest version---      2. If the versions are the same, prefer the package that---      came in the latest package database.------ Pursuant to #12518, we could change this policy to, for example, remove--- the version preference, meaning that we would always prefer the units--- in later unit database.-compareByPreference-    :: UnitPrecedenceMap-    -> UnitInfo-    -> UnitInfo-    -> Ordering-compareByPreference prec_map pkg pkg'-  = case comparing unitPackageVersion pkg pkg' of-        GT -> GT-        EQ | Just prec  <- lookupUniqMap prec_map (unitId pkg)-           , Just prec' <- lookupUniqMap prec_map (unitId pkg')-           -- Prefer the unit from the later DB flag (i.e., higher-           -- precedence)-           -> compare prec prec'-           | otherwise-           -> EQ-        LT -> LT--comparing :: Ord a => (t -> a) -> t -> t -> Ordering-comparing f a b = f a `compare` f b--pprFlag :: PackageFlag -> SDoc-pprFlag flag = case flag of-    HidePackage p   -> text "-hide-package " <> text p-    ExposePackage doc _ _ -> text doc--pprTrustFlag :: TrustFlag -> SDoc-pprTrustFlag flag = case flag of-    TrustPackage p    -> text "-trust " <> text p-    DistrustPackage p -> text "-distrust " <> text p---- -------------------------------------------------------------------------------- Wired-in units------ See Note [Wired-in units] in GHC.Unit.Types--type WiringMap = UniqMap UnitId UnitId--findWiredInUnits-   :: Logger-   -> UnitPrecedenceMap-   -> [UnitInfo]           -- database-   -> VisibilityMap             -- info on what units are visible-                                -- for wired in selection-   -> IO ([UnitInfo],  -- unit database updated for wired in-          WiringMap)   -- map from unit id to wired identity--findWiredInUnits logger prec_map pkgs vis_map = do-  -- Now we must find our wired-in units, and rename them to-  -- their canonical names (eg. base-1.0 ==> base), as described-  -- in Note [Wired-in units] in GHC.Unit.Types-  let-        matches :: UnitInfo -> UnitId -> Bool-        pc `matches` pid = unitPackageName pc == PackageName (unitIdFS pid)--        -- find which package corresponds to each wired-in package-        -- delete any other packages with the same name-        -- update the package and any dependencies to point to the new-        -- one.-        ---        -- When choosing which package to map to a wired-in package-        -- name, we try to pick the latest version of exposed packages.-        -- However, if there are no exposed wired in packages available-        -- (e.g. -hide-all-packages was used), we can't bail: we *have*-        -- to assign a package for the wired-in package: so we try again-        -- with hidden packages included to (and pick the latest-        -- version).-        ---        -- You can also override the default choice by using -ignore-package:-        -- this works even when there is no exposed wired in package-        -- available.-        ---        findWiredInUnit :: [UnitInfo] -> UnitId -> IO (Maybe (UnitId, UnitInfo))-        findWiredInUnit pkgs wired_pkg = firstJustsM [try all_exposed_ps, try all_ps, notfound]-          where-                all_ps = [ p | p <- pkgs, p `matches` wired_pkg ]-                all_exposed_ps = [ p | p <- all_ps, (mkUnit p) `elemUniqMap` vis_map ]--                try ps = case sortByPreference prec_map ps of-                    p:_ -> Just <$> pick p-                    _ -> pure Nothing--                notfound = do-                          debugTraceMsg logger 2 $-                            text "wired-in package "-                                 <> ftext (unitIdFS wired_pkg)-                                 <> text " not found."-                          return Nothing-                pick :: UnitInfo -> IO (UnitId, UnitInfo)-                pick pkg = do-                        debugTraceMsg logger 2 $-                            text "wired-in package "-                                 <> ftext (unitIdFS wired_pkg)-                                 <> text " mapped to "-                                 <> ppr (unitId pkg)-                        return (wired_pkg, pkg)---  mb_wired_in_pkgs <- mapM (findWiredInUnit pkgs) wiredInUnitIds-  let-        wired_in_pkgs = catMaybes mb_wired_in_pkgs--        wiredInMap :: UniqMap UnitId UnitId-        wiredInMap = listToUniqMap-          [ (unitId realUnitInfo, wiredInUnitId)-          | (wiredInUnitId, realUnitInfo) <- wired_in_pkgs-          , not (unitIsIndefinite realUnitInfo)-          ]--        updateWiredInDependencies pkgs = map (upd_deps . upd_pkg) pkgs-          where upd_pkg pkg-                  | Just wiredInUnitId <- lookupUniqMap wiredInMap (unitId pkg)-                  = pkg { unitId         = wiredInUnitId-                        , unitInstanceOf = wiredInUnitId-                           -- every non instantiated unit is an instance of-                           -- itself (required by Backpack...)-                           ---                           -- See Note [About units] in GHC.Unit-                        }-                  | otherwise-                  = pkg-                upd_deps pkg = pkg {-                      unitDepends = map (upd_wired_in wiredInMap) (unitDepends pkg),-                      unitExposedModules-                        = map (\(k,v) -> (k, fmap (upd_wired_in_mod wiredInMap) v))-                              (unitExposedModules pkg)-                    }---  return (updateWiredInDependencies pkgs, wiredInMap)---- Helper functions for rewiring Module and Unit.  These--- rewrite Units of modules in wired-in packages to the form known to the--- compiler, as described in Note [Wired-in units] in GHC.Unit.Types.------ For instance, base-4.9.0.0 will be rewritten to just base, to match--- what appears in GHC.Builtin.Names.--upd_wired_in_mod :: WiringMap -> Module -> Module-upd_wired_in_mod wiredInMap (Module uid m) = Module (upd_wired_in_uid wiredInMap uid) m--upd_wired_in_uid :: WiringMap -> Unit -> Unit-upd_wired_in_uid wiredInMap u = case u of-   HoleUnit -> HoleUnit-   RealUnit (Definite uid) -> RealUnit (Definite (upd_wired_in wiredInMap uid))-   VirtUnit indef_uid ->-      VirtUnit $ mkInstantiatedUnit-        (instUnitInstanceOf indef_uid)-        (map (\(x,y) -> (x,upd_wired_in_mod wiredInMap y)) (instUnitInsts indef_uid))--upd_wired_in :: WiringMap -> UnitId -> UnitId-upd_wired_in wiredInMap key-    | Just key' <- lookupUniqMap wiredInMap key = key'-    | otherwise = key--updateVisibilityMap :: WiringMap -> VisibilityMap -> VisibilityMap-updateVisibilityMap wiredInMap vis_map = foldl' f vis_map (nonDetUniqMapToList wiredInMap)-  where f vm (from, to) = case lookupUniqMap vis_map (RealUnit (Definite from)) of-                    Nothing -> vm-                    Just r -> addToUniqMap (delFromUniqMap vm (RealUnit (Definite from)))-                              (RealUnit (Definite to)) r--  -- -------------------------------------------------------------------------------- | The reason why a unit is unusable.-data UnusableUnitReason-  = -- | We ignored it explicitly using @-ignore-package@.-    IgnoredWithFlag-    -- | This unit transitively depends on a unit that was never present-    -- in any of the provided databases.-  | BrokenDependencies   [UnitId]-    -- | This unit transitively depends on a unit involved in a cycle.-    -- Note that the list of 'UnitId' reports the direct dependencies-    -- of this unit that (transitively) depended on the cycle, and not-    -- the actual cycle itself (which we report separately at high verbosity.)-  | CyclicDependencies   [UnitId]-    -- | This unit transitively depends on a unit which was ignored.-  | IgnoredDependencies  [UnitId]-    -- | This unit transitively depends on a unit which was-    -- shadowed by an ABI-incompatible unit.-  | ShadowedDependencies [UnitId]--instance Outputable UnusableUnitReason where-    ppr IgnoredWithFlag = text "[ignored with flag]"-    ppr (BrokenDependencies uids)   = brackets (text "broken" <+> ppr uids)-    ppr (CyclicDependencies uids)   = brackets (text "cyclic" <+> ppr uids)-    ppr (IgnoredDependencies uids)  = brackets (text "ignored" <+> ppr uids)-    ppr (ShadowedDependencies uids) = brackets (text "shadowed" <+> ppr uids)--type UnusableUnits = UniqMap UnitId (UnitInfo, UnusableUnitReason)--pprReason :: SDoc -> UnusableUnitReason -> SDoc-pprReason pref reason = case reason of-  IgnoredWithFlag ->-      pref <+> text "ignored due to an -ignore-package flag"-  BrokenDependencies deps ->-      pref <+> text "unusable due to missing dependencies:" $$-        nest 2 (hsep (map ppr deps))-  CyclicDependencies deps ->-      pref <+> text "unusable due to cyclic dependencies:" $$-        nest 2 (hsep (map ppr deps))-  IgnoredDependencies deps ->-      pref <+> text ("unusable because the -ignore-package flag was used to " ++-                     "ignore at least one of its dependencies:") $$-        nest 2 (hsep (map ppr deps))-  ShadowedDependencies deps ->-      pref <+> text "unusable due to shadowed dependencies:" $$-        nest 2 (hsep (map ppr deps))--reportCycles :: Logger -> [SCC UnitInfo] -> IO ()-reportCycles logger sccs = mapM_ report sccs-  where-    report (AcyclicSCC _) = return ()-    report (CyclicSCC vs) =-        debugTraceMsg logger 2 $-          text "these packages are involved in a cycle:" $$-            nest 2 (hsep (map (ppr . unitId) vs))--reportUnusable :: Logger -> UnusableUnits -> IO ()-reportUnusable logger pkgs = mapM_ report (nonDetUniqMapToList pkgs)-  where-    report (ipid, (_, reason)) =-       debugTraceMsg logger 2 $-         pprReason-           (text "package" <+> ppr ipid <+> text "is") reason---- ---------------------------------------------------------------------------------- Utilities on the database------- | A reverse dependency index, mapping an 'UnitId' to--- the 'UnitId's which have a dependency on it.-type RevIndex = UniqMap UnitId [UnitId]---- | Compute the reverse dependency index of a unit database.-reverseDeps :: UnitInfoMap -> RevIndex-reverseDeps db = nonDetFoldUniqMap go emptyUniqMap db-  where-    go :: (UnitId, UnitInfo) -> RevIndex -> RevIndex-    go (_uid, pkg) r = foldl' (go' (unitId pkg)) r (unitDepends pkg)-    go' from r to = addToUniqMap_C (++) r to [from]---- | Given a list of 'UnitId's to remove, a database,--- and a reverse dependency index (as computed by 'reverseDeps'),--- remove those units, plus any units which depend on them.--- Returns the pruned database, as well as a list of 'UnitInfo's--- that was removed.-removeUnits :: [UnitId] -> RevIndex-               -> UnitInfoMap-               -> (UnitInfoMap, [UnitInfo])-removeUnits uids index m = go uids (m,[])-  where-    go [] (m,pkgs) = (m,pkgs)-    go (uid:uids) (m,pkgs)-        | Just pkg <- lookupUniqMap m uid-        = case lookupUniqMap index uid of-            Nothing    -> go uids (delFromUniqMap m uid, pkg:pkgs)-            Just rdeps -> go (rdeps ++ uids) (delFromUniqMap m uid, pkg:pkgs)-        | otherwise-        = go uids (m,pkgs)---- | Given a 'UnitInfo' from some 'UnitInfoMap', return all entries in 'depends'--- which correspond to units that do not exist in the index.-depsNotAvailable :: UnitInfoMap-                 -> UnitInfo-                 -> [UnitId]-depsNotAvailable pkg_map pkg = filter (not . (`elemUniqMap` pkg_map)) (unitDepends pkg)---- | Given a 'UnitInfo' from some 'UnitInfoMap' return all entries in--- 'unitAbiDepends' which correspond to units that do not exist, OR have--- mismatching ABIs.-depsAbiMismatch :: UnitInfoMap-                -> UnitInfo-                -> [UnitId]-depsAbiMismatch pkg_map pkg = map fst . filter (not . abiMatch) $ unitAbiDepends pkg-  where-    abiMatch (dep_uid, abi)-        | Just dep_pkg <- lookupUniqMap pkg_map dep_uid-        = unitAbiHash dep_pkg == abi-        | otherwise-        = False---- -------------------------------------------------------------------------------- Ignore units--ignoreUnits :: [IgnorePackageFlag] -> [UnitInfo] -> UnusableUnits-ignoreUnits flags pkgs = listToUniqMap (concatMap doit flags)-  where-  doit (IgnorePackage str) =-     case partition (matchingStr str) pkgs of-         (ps, _) -> [ (unitId p, (p, IgnoredWithFlag))-                    | p <- ps ]-        -- missing unit is not an error for -ignore-package,-        -- because a common usage is to -ignore-package P as-        -- a preventative measure just in case P exists.---- ---------------------------------------------------------------------------------- Merging databases------- | For each unit, a mapping from uid -> i indicates that this--- unit was brought into GHC by the ith @-package-db@ flag on--- the command line.  We use this mapping to make sure we prefer--- units that were defined later on the command line, if there--- is an ambiguity.-type UnitPrecedenceMap = UniqMap UnitId Int---- | Given a list of databases, merge them together, where--- units with the same unit id in later databases override--- earlier ones.  This does NOT check if the resulting database--- makes sense (that's done by 'validateDatabase').-mergeDatabases :: Logger -> [UnitDatabase UnitId]-               -> IO (UnitInfoMap, UnitPrecedenceMap)-mergeDatabases logger = foldM merge (emptyUniqMap, emptyUniqMap) . zip [1..]-  where-    merge (pkg_map, prec_map) (i, UnitDatabase db_path db) = do-      debugTraceMsg logger 2 $-          text "loading package database" <+> text db_path-      forM_ (Set.toList override_set) $ \pkg ->-          debugTraceMsg logger 2 $-              text "package" <+> ppr pkg <+>-              text "overrides a previously defined package"-      return (pkg_map', prec_map')-     where-      db_map = mk_pkg_map db-      mk_pkg_map = listToUniqMap . map (\p -> (unitId p, p))--      -- The set of UnitIds which appear in both db and pkgs.  These are the-      -- ones that get overridden.  Compute this just to give some-      -- helpful debug messages at -v2-      override_set :: Set UnitId-      override_set = Set.intersection (nonDetUniqMapToKeySet db_map)-                                      (nonDetUniqMapToKeySet pkg_map)--      -- Now merge the sets together (NB: in case of duplicate,-      -- first argument preferred)-      pkg_map' :: UnitInfoMap-      pkg_map' = pkg_map `plusUniqMap` db_map--      prec_map' :: UnitPrecedenceMap-      prec_map' = prec_map `plusUniqMap` (mapUniqMap (const i) db_map)---- | Validates a database, removing unusable units from it--- (this includes removing units that the user has explicitly--- ignored.)  Our general strategy:------ 1. Remove all broken units (dangling dependencies)--- 2. Remove all units that are cyclic--- 3. Apply ignore flags--- 4. Remove all units which have deps with mismatching ABIs----validateDatabase :: UnitConfig -> UnitInfoMap-                 -> (UnitInfoMap, UnusableUnits, [SCC UnitInfo])-validateDatabase cfg pkg_map1 =-    (pkg_map5, unusable, sccs)-  where-    ignore_flags = reverse (unitConfigFlagsIgnored cfg)--    -- Compute the reverse dependency index-    index = reverseDeps pkg_map1--    -- Helper function-    mk_unusable mk_err dep_matcher m uids =-      listToUniqMap [ (unitId pkg, (pkg, mk_err (dep_matcher m pkg)))-                    | pkg <- uids-                    ]--    -- Find broken units-    directly_broken = filter (not . null . depsNotAvailable pkg_map1)-                             (nonDetEltsUniqMap pkg_map1)-    (pkg_map2, broken) = removeUnits (map unitId directly_broken) index pkg_map1-    unusable_broken = mk_unusable BrokenDependencies depsNotAvailable pkg_map2 broken--    -- Find recursive units-    sccs = stronglyConnComp [ (pkg, unitId pkg, unitDepends pkg)-                            | pkg <- nonDetEltsUniqMap pkg_map2 ]-    getCyclicSCC (CyclicSCC vs) = map unitId vs-    getCyclicSCC (AcyclicSCC _) = []-    (pkg_map3, cyclic) = removeUnits (concatMap getCyclicSCC sccs) index pkg_map2-    unusable_cyclic = mk_unusable CyclicDependencies depsNotAvailable pkg_map3 cyclic--    -- Apply ignore flags-    directly_ignored = ignoreUnits ignore_flags (nonDetEltsUniqMap pkg_map3)-    (pkg_map4, ignored) = removeUnits (nonDetKeysUniqMap directly_ignored) index pkg_map3-    unusable_ignored = mk_unusable IgnoredDependencies depsNotAvailable pkg_map4 ignored--    -- Knock out units whose dependencies don't agree with ABI-    -- (i.e., got invalidated due to shadowing)-    directly_shadowed = filter (not . null . depsAbiMismatch pkg_map4)-                               (nonDetEltsUniqMap pkg_map4)-    (pkg_map5, shadowed) = removeUnits (map unitId directly_shadowed) index pkg_map4-    unusable_shadowed = mk_unusable ShadowedDependencies depsAbiMismatch pkg_map5 shadowed--    -- combine all unusables. The order is important for shadowing.-    -- plusUniqMapList folds using plusUFM which is right biased (opposite of-    -- Data.Map.union) so the head of the list should be the least preferred-    unusable = plusUniqMapList [ unusable_shadowed-                               , unusable_cyclic-                               , unusable_broken-                               , unusable_ignored-                               , directly_ignored-                               ]---- -------------------------------------------------------------------------------- When all the command-line options are in, we can process our unit--- settings and populate the unit state.--mkUnitState-    :: Logger-    -> UnitConfig-    -> IO (UnitState,[UnitDatabase UnitId])-mkUnitState logger cfg = do-{--   Plan.--   There are two main steps for making the package state:--    1. We want to build a single, unified package database based-       on all of the input databases, which upholds the invariant that-       there is only one package per any UnitId and there are no-       dangling dependencies.  We'll do this by merging, and-       then successively filtering out bad dependencies.--       a) Merge all the databases together.-          If an input database defines unit ID that is already in-          the unified database, that package SHADOWS the existing-          package in the current unified database.  Note that-          order is important: packages defined later in the list of-          command line arguments shadow those defined earlier.--       b) Remove all packages with missing dependencies, or-          mutually recursive dependencies.--       b) Remove packages selected by -ignore-package from input database--       c) Remove all packages which depended on packages that are now-          shadowed by an ABI-incompatible package--       d) report (with -v) any packages that were removed by steps 1-3--    2. We want to look at the flags controlling package visibility,-       and build a mapping of what module names are in scope and-       where they live.--       a) on the final, unified database, we apply -trust/-distrust-          flags directly, modifying the database so that the 'trusted'-          field has the correct value.--       b) we use the -package/-hide-package flags to compute a-          visibility map, stating what packages are "exposed" for-          the purposes of computing the module map.-          * if any flag refers to a package which was removed by 1-5, then-            we can give an error message explaining why-          * if -hide-all-packages was not specified, this step also-            hides packages which are superseded by later exposed packages-          * this step is done TWICE if -plugin-package/-hide-all-plugin-packages-            are used--       c) based on the visibility map, we pick wired packages and rewrite-          them to have the expected unitId.--       d) finally, using the visibility map and the package database,-          we build a mapping saying what every in scope module name points to.--}--  -- if databases have not been provided, read the database flags-  raw_dbs <- case unitConfigDBCache cfg of-               Nothing  -> readUnitDatabases logger cfg-               Just dbs -> return dbs--  -- distrust all units if the flag is set-  let distrust_all db = db { unitDatabaseUnits = distrustAllUnits (unitDatabaseUnits db) }-      dbs | unitConfigDistrustAll cfg = map distrust_all raw_dbs-          | otherwise                 = raw_dbs---  -- This, and the other reverse's that you will see, are due to the fact that-  -- packageFlags, pluginPackageFlags, etc. are all specified in *reverse* order-  -- than they are on the command line.-  let raw_other_flags = reverse (unitConfigFlagsExposed cfg)-      (hpt_flags, other_flags) = partition (selectHptFlag (unitConfigHomeUnits cfg)) raw_other_flags-  debugTraceMsg logger 2 $-      text "package flags" <+> ppr other_flags--  let home_unit_deps = selectHomeUnits (unitConfigHomeUnits cfg) hpt_flags--  -- Merge databases together, without checking validity-  (pkg_map1, prec_map) <- mergeDatabases logger dbs--  -- Now that we've merged everything together, prune out unusable-  -- packages.-  let (pkg_map2, unusable, sccs) = validateDatabase cfg pkg_map1--  reportCycles   logger sccs-  reportUnusable logger unusable--  -- Apply trust flags (these flags apply regardless of whether-  -- or not packages are visible or not)-  pkgs1 <- mayThrowUnitErr-            $ foldM (applyTrustFlag prec_map unusable)-                 (nonDetEltsUniqMap pkg_map2) (reverse (unitConfigFlagsTrusted cfg))-  let prelim_pkg_db = mkUnitInfoMap pkgs1--  ---  -- Calculate the initial set of units from package databases, prior to any package flags.-  ---  -- Conceptually, we select the latest versions of all valid (not unusable) *packages*-  -- (not units). This is empty if we have -hide-all-packages.-  ---  -- Then we create an initial visibility map with default visibilities for all-  -- exposed, definite units which belong to the latest valid packages.-  ---  let preferLater unit unit' =-        case compareByPreference prec_map unit unit' of-            GT -> unit-            _  -> unit'-      addIfMorePreferable m unit = addToUDFM_C preferLater m (fsPackageName unit) unit-      -- This is the set of maximally preferable packages. In fact, it is a set of-      -- most preferable *units* keyed by package name, which act as stand-ins in-      -- for "a package in a database". We use units here because we don't have-      -- "a package in a database" as a type currently.-      mostPreferablePackageReps = if unitConfigHideAll cfg-                    then emptyUDFM-                    else foldl' addIfMorePreferable emptyUDFM pkgs1-      -- When exposing units, we want to consider all of those in the most preferable-      -- packages. We can implement that by looking for units that are equi-preferable-      -- with the most preferable unit for package. Being equi-preferable means that-      -- they must be in the same database, with the same version, and the same package name.-      ---      -- We must take care to consider all these units and not just the most-      -- preferable one, otherwise we can end up with problems like #16228.-      mostPreferable u =-        case lookupUDFM mostPreferablePackageReps (fsPackageName u) of-          Nothing -> False-          Just u' -> compareByPreference prec_map u u' == EQ-      vis_map1 = foldl' (\vm p ->-                            -- Note: we NEVER expose indefinite packages by-                            -- default, because it's almost assuredly not-                            -- what you want (no mix-in linking has occurred).-                            if unitIsExposed p && unitIsDefinite (mkUnit p) && mostPreferable p-                               then addToUniqMap vm (mkUnit p)-                                               UnitVisibility {-                                                 uv_expose_all = True,-                                                 uv_renamings = [],-                                                 uv_package_name = First (Just (fsPackageName p)),-                                                 uv_requirements = emptyUniqMap,-                                                 uv_explicit = Nothing-                                               }-                               else vm)-                         emptyUniqMap pkgs1--  ---  -- Compute a visibility map according to the command-line flags (-package,-  -- -hide-package).  This needs to know about the unusable packages, since if a-  -- user tries to enable an unusable package, we should let them know.-  ---  vis_map2 <- mayThrowUnitErr-                $ foldM (applyPackageFlag prec_map prelim_pkg_db emptyUniqSet unusable-                        (unitConfigHideAll cfg) pkgs1)-                            vis_map1 other_flags--  ---  -- Sort out which packages are wired in. This has to be done last, since-  -- it modifies the unit ids of wired in packages, but when we process-  -- package arguments we need to key against the old versions.-  ---  (pkgs2, wired_map) <- findWiredInUnits logger prec_map pkgs1 vis_map2-  let pkg_db = mkUnitInfoMap pkgs2--  -- Update the visibility map, so we treat wired packages as visible.-  let vis_map = updateVisibilityMap wired_map vis_map2--  let hide_plugin_pkgs = unitConfigHideAllPlugins cfg-  plugin_vis_map <--    case unitConfigFlagsPlugins cfg of-        -- common case; try to share the old vis_map-        [] | not hide_plugin_pkgs -> return vis_map-           | otherwise -> return emptyUniqMap-        _ -> do let plugin_vis_map1-                        | hide_plugin_pkgs = emptyUniqMap-                        -- Use the vis_map PRIOR to wired in,-                        -- because otherwise applyPackageFlag-                        -- won't work.-                        | otherwise = vis_map2-                plugin_vis_map2-                    <- mayThrowUnitErr-                        $ foldM (applyPackageFlag prec_map prelim_pkg_db emptyUniqSet unusable-                                hide_plugin_pkgs pkgs1)-                             plugin_vis_map1-                             (reverse (unitConfigFlagsPlugins cfg))-                -- Updating based on wired in packages is mostly-                -- good hygiene, because it won't matter: no wired in-                -- package has a compiler plugin.-                -- TODO: If a wired in package had a compiler plugin,-                -- and you tried to pick different wired in packages-                -- with the plugin flags and the normal flags... what-                -- would happen?  I don't know!  But this doesn't seem-                -- likely to actually happen.-                return (updateVisibilityMap wired_map plugin_vis_map2)--  let pkgname_map = listToUFM [ (unitPackageName p, unitInstanceOf p)-                              | p <- pkgs2-                              ]-  -- The explicitUnits accurately reflects the set of units we have turned-  -- on; as such, it also is the only way one can come up with requirements.-  -- The requirement context is directly based off of this: we simply-  -- look for nested unit IDs that are directly fed holes: the requirements-  -- of those units are precisely the ones we need to track-  let explicit_pkgs = [(k, uv_explicit v) | (k, v) <- nonDetUniqMapToList vis_map]-      req_ctx = mapUniqMap (Set.toList)-              $ plusUniqMapListWith Set.union (map uv_requirements (nonDetEltsUniqMap vis_map))---  ---  -- Here we build up a set of the packages mentioned in -package-  -- flags on the command line; these are called the "preload"-  -- packages.  we link these packages in eagerly.  The preload set-  -- should contain at least rts & base, which is why we pretend that-  -- the command line contains -package rts & -package base.-  ---  -- NB: preload IS important even for type-checking, because we-  -- need the correct include path to be set.-  ---  let preload1 = nonDetKeysUniqMap (filterUniqMap (isJust . uv_explicit) vis_map)--      -- add default preload units if they can be found in the db-      basicLinkedUnits = fmap (RealUnit . Definite)-                         $ filter (flip elemUniqMap pkg_db)-                         $ unitConfigAutoLink cfg-      preload3 = ordNub $ (basicLinkedUnits ++ preload1)--  -- Close the preload packages with their dependencies-  dep_preload <- mayThrowUnitErr-                    $ closeUnitDeps pkg_db-                    $ zip (map toUnitId preload3) (repeat Nothing)--  let mod_map1 = mkModuleNameProvidersMap logger cfg pkg_db emptyUniqSet vis_map-      mod_map2 = mkUnusableModuleNameProvidersMap unusable-      mod_map = mod_map2 `plusUniqMap` mod_map1--  -- Force the result to avoid leaking input parameters-  let !state = UnitState-         { preloadUnits                 = dep_preload-         , explicitUnits                = explicit_pkgs-         , homeUnitDepends              = Set.toList home_unit_deps-         , unitInfoMap                  = pkg_db-         , preloadClosure               = emptyUniqSet-         , moduleNameProvidersMap       = mod_map-         , pluginModuleNameProvidersMap = mkModuleNameProvidersMap logger cfg pkg_db emptyUniqSet plugin_vis_map-         , packageNameMap               = pkgname_map-         , wireMap                      = wired_map-         , unwireMap                    = listToUniqMap [ (v,k) | (k,v) <- nonDetUniqMapToList wired_map ]-         , requirementContext           = req_ctx-         , allowVirtualUnits            = unitConfigAllowVirtual cfg-         }-  return (state, raw_dbs)--selectHptFlag :: Set.Set UnitId -> PackageFlag -> Bool-selectHptFlag home_units (ExposePackage _ (UnitIdArg uid) _) | toUnitId uid `Set.member` home_units = True-selectHptFlag _ _ = False--selectHomeUnits :: Set.Set UnitId -> [PackageFlag] -> Set.Set UnitId-selectHomeUnits home_units flags = foldl' go Set.empty flags-  where-    go :: Set.Set UnitId -> PackageFlag -> Set.Set UnitId-    go cur (ExposePackage _ (UnitIdArg uid) _) | toUnitId uid `Set.member` home_units = Set.insert (toUnitId uid) cur-    -- MP: This does not yet support thinning/renaming-    go cur _ = cur----- | Given a wired-in 'Unit', "unwire" it into the 'Unit'--- that it was recorded as in the package database.-unwireUnit :: UnitState -> Unit -> Unit-unwireUnit state uid@(RealUnit (Definite def_uid)) =-    maybe uid (RealUnit . Definite) (lookupUniqMap (unwireMap state) def_uid)-unwireUnit _ uid = uid---- -------------------------------------------------------------------------------- | Makes the mapping from ModuleName to package info---- Slight irritation: we proceed by leafing through everything--- in the installed package database, which makes handling indefinite--- packages a bit bothersome.--mkModuleNameProvidersMap-  :: Logger-  -> UnitConfig-  -> UnitInfoMap-  -> PreloadUnitClosure-  -> VisibilityMap-  -> ModuleNameProvidersMap-mkModuleNameProvidersMap logger cfg pkg_map closure vis_map =-    -- What should we fold on?  Both situations are awkward:-    ---    --    * Folding on the visibility map means that we won't create-    --      entries for packages that aren't mentioned in vis_map-    --      (e.g., hidden packages, causing #14717)-    ---    --    * Folding on pkg_map is awkward because if we have an-    --      Backpack instantiation, we need to possibly add a-    --      package from pkg_map multiple times to the actual-    --      ModuleNameProvidersMap.  Also, we don't really want-    --      definite package instantiations to show up in the-    --      list of possibilities.-    ---    -- So what will we do instead?  We'll extend vis_map with-    -- entries for every definite (for non-Backpack) and-    -- indefinite (for Backpack) package, so that we get the-    -- hidden entries we need.-    nonDetFoldUniqMap extend_modmap emptyMap vis_map_extended- where-  vis_map_extended = {- preferred -} default_vis `plusUniqMap` vis_map--  default_vis = listToUniqMap-                  [ (mkUnit pkg, mempty)-                  | (_, pkg) <- nonDetUniqMapToList pkg_map-                  -- Exclude specific instantiations of an indefinite-                  -- package-                  , unitIsIndefinite pkg || null (unitInstantiations pkg)-                  ]--  emptyMap = emptyUniqMap-  setOrigins m os = fmap (const os) m-  extend_modmap (uid, UnitVisibility { uv_expose_all = b, uv_renamings = rns }) modmap-    = addListTo modmap theBindings-   where-    pkg = unit_lookup uid--    theBindings :: [(ModuleName, UniqMap Module ModuleOrigin)]-    theBindings = newBindings b rns--    newBindings :: Bool-                -> [(ModuleName, ModuleName)]-                -> [(ModuleName, UniqMap Module ModuleOrigin)]-    newBindings e rns  = es e ++ hiddens ++ map rnBinding rns--    rnBinding :: (ModuleName, ModuleName)-              -> (ModuleName, UniqMap Module ModuleOrigin)-    rnBinding (orig, new) = (new, setOrigins origEntry fromFlag)-     where origEntry = case lookupUFM esmap orig of-            Just r -> r-            Nothing -> throwGhcException (CmdLineError (renderWithContext-                        (log_default_user_context (logFlags logger))-                        (text "package flag: could not find module name" <+>-                            ppr orig <+> text "in package" <+> ppr pk)))--    es :: Bool -> [(ModuleName, UniqMap Module ModuleOrigin)]-    es e = do-     (m, exposedReexport) <- exposed_mods-     let (pk', m', origin') =-          case exposedReexport of-           Nothing -> (pk, m, fromExposedModules e)-           Just (Module pk' m') ->-              (pk', m', fromReexportedModules e pkg)-     return (m, mkModMap pk' m' origin')--    esmap :: UniqFM ModuleName (UniqMap Module ModuleOrigin)-    esmap = listToUFM (es False) -- parameter here doesn't matter, orig will-                                 -- be overwritten--    hiddens = [(m, mkModMap pk m ModHidden) | m <- hidden_mods]--    pk = mkUnit pkg-    unit_lookup uid = lookupUnit' (unitConfigAllowVirtual cfg) pkg_map closure uid-                        `orElse` pprPanic "unit_lookup" (ppr uid)--    exposed_mods = unitExposedModules pkg-    hidden_mods  = unitHiddenModules pkg---- | Make a 'ModuleNameProvidersMap' covering a set of unusable packages.-mkUnusableModuleNameProvidersMap :: UnusableUnits -> ModuleNameProvidersMap-mkUnusableModuleNameProvidersMap unusables =-    nonDetFoldUniqMap extend_modmap emptyUniqMap unusables- where-    extend_modmap (_uid, (unit_info, reason)) modmap = addListTo modmap bindings-      where bindings :: [(ModuleName, UniqMap Module ModuleOrigin)]-            bindings = exposed ++ hidden--            origin_reexport =  ModUnusable (UnusableUnit unit reason True)-            origin_normal   =  ModUnusable (UnusableUnit unit reason False)-            unit = mkUnit unit_info--            exposed = map get_exposed exposed_mods-            hidden = [(m, mkModMap unit m origin_normal) | m <- hidden_mods]--            -- with re-exports, c:Foo can be reexported from two (or more)-            -- unusable packages:-            --  Foo -> a:Foo (unusable reason A) -> c:Foo-            --      -> b:Foo (unusable reason B) -> c:Foo-            ---            -- We must be careful to not record the following (#21097):-            --  Foo -> c:Foo (unusable reason A)-            --      -> c:Foo (unusable reason B)-            -- But:-            --  Foo -> a:Foo (unusable reason A)-            --      -> b:Foo (unusable reason B)-            ---            get_exposed (mod, Just _) = (mod, mkModMap unit mod origin_reexport)-            get_exposed (mod, _) = (mod, mkModMap unit mod origin_normal)-              -- in the reexport case, we create a virtual module that doesn't-              -- exist but we don't care as it's only used as a key in the map.--            exposed_mods = unitExposedModules unit_info-            hidden_mods  = unitHiddenModules  unit_info---- | Add a list of key/value pairs to a nested map.------ The outer map is processed with 'Data.Map.Strict' to prevent memory leaks--- when reloading modules in GHCi (see #4029). This ensures that each--- value is forced before installing into the map.-addListTo :: (Monoid a, Ord k1, Ord k2, Uniquable k1, Uniquable k2)-          => UniqMap k1 (UniqMap k2 a)-          -> [(k1, UniqMap k2 a)]-          -> UniqMap k1 (UniqMap k2 a)-addListTo = foldl' merge-  where merge m (k, v) = addToUniqMap_C (plusUniqMap_C mappend) m k v---- | Create a singleton module mapping-mkModMap :: Unit -> ModuleName -> ModuleOrigin -> UniqMap Module ModuleOrigin-mkModMap pkg mod = unitUniqMap (mkModule pkg mod)----- -------------------------------------------------------------------------------- Package Utils---- | Takes a 'ModuleName', and if the module is in any package returns--- list of modules which take that name.-lookupModuleInAllUnits :: UnitState-                          -> ModuleName-                          -> [(Module, UnitInfo)]-lookupModuleInAllUnits pkgs m-  = case lookupModuleWithSuggestions pkgs m NoPkgQual of-      LookupFound a b -> [(a,fst b)]-      LookupMultiple rs -> map f rs-        where f (m,_) = (m, expectJust (lookupUnit pkgs (moduleUnit m)))-      _ -> []---- | The result of performing a lookup-data LookupResult =-    -- | Found the module uniquely, nothing else to do-    LookupFound Module (UnitInfo, ModuleOrigin)-    -- | Multiple modules with the same name in scope-  | LookupMultiple [(Module, ModuleOrigin)]-    -- | No modules found, but there were some hidden ones with-    -- an exact name match.  First is due to package hidden, second-    -- is due to module being hidden-  | LookupHidden [(Module, ModuleOrigin)] [(Module, ModuleOrigin)]-    -- | No modules found, but there were some unusable ones with-    -- an exact name match-  | LookupUnusable [(Module, ModuleOrigin)]-    -- | Nothing found, here are some suggested different names-  | LookupNotFound [ModuleSuggestion] -- suggestions--data ModuleSuggestion = SuggestVisible ModuleName Module ModuleOrigin-                      | SuggestHidden ModuleName Module ModuleOrigin--lookupModuleWithSuggestions :: UnitState-                            -> ModuleName-                            -> PkgQual-                            -> LookupResult-lookupModuleWithSuggestions pkgs-  = lookupModuleWithSuggestions' pkgs (moduleNameProvidersMap pkgs)---- | The package which the module **appears** to come from, this could be--- the one which reexports the module from it's original package. This function--- is currently only used for -Wunused-packages-lookupModulePackage :: UnitState -> ModuleName -> PkgQual -> Maybe [UnitInfo]-lookupModulePackage pkgs mn mfs =-    case lookupModuleWithSuggestions' pkgs (moduleNameProvidersMap pkgs) mn mfs of-      LookupFound _ (orig_unit, origin) ->-        case origin of-          ModOrigin {fromOrigUnit, fromExposedReexport} ->-            case fromOrigUnit of-              -- Just True means, the import is available from its original location-              Just True ->-                pure [orig_unit]-              -- Otherwise, it must be available from a reexport-              _ -> pure fromExposedReexport--          _ -> Nothing--      _ -> Nothing--lookupPluginModuleWithSuggestions :: UnitState-                                  -> ModuleName-                                  -> PkgQual-                                  -> LookupResult-lookupPluginModuleWithSuggestions pkgs-  = lookupModuleWithSuggestions' pkgs (pluginModuleNameProvidersMap pkgs)--lookupModuleWithSuggestions' :: UnitState-                            -> ModuleNameProvidersMap-                            -> ModuleName-                            -> PkgQual-                            -> LookupResult-lookupModuleWithSuggestions' pkgs mod_map m mb_pn-  = case lookupUniqMap mod_map m of-        Nothing -> LookupNotFound suggestions-        Just xs ->-          case foldl' classify ([],[],[], []) (sortOn fst $ nonDetUniqMapToList xs) of-            ([], [], [], []) -> LookupNotFound suggestions-            (_, _, _, [(m, o)])             -> LookupFound m (mod_unit m, o)-            (_, _, _, exposed@(_:_))        -> LookupMultiple exposed-            ([], [], unusable@(_:_), [])    -> LookupUnusable unusable-            (hidden_pkg, hidden_mod, _, []) ->-              LookupHidden hidden_pkg hidden_mod-  where-    classify (hidden_pkg, hidden_mod, unusable, exposed) (m, origin0) =-      let origin = filterOrigin mb_pn (mod_unit m) origin0-          x = (m, origin)-      in case origin of-          ModHidden-            -> (hidden_pkg, x:hidden_mod, unusable, exposed)-          ModUnusable _-            -> (hidden_pkg, hidden_mod, x:unusable, exposed)-          _ | originEmpty origin-            -> (hidden_pkg,   hidden_mod, unusable, exposed)-            | originVisible origin-            -> (hidden_pkg, hidden_mod, unusable, x:exposed)-            | otherwise-            -> (x:hidden_pkg, hidden_mod, unusable, exposed)--    unit_lookup p = lookupUnit pkgs p `orElse` pprPanic "lookupModuleWithSuggestions" (ppr p <+> ppr m)-    mod_unit = unit_lookup . moduleUnit--    -- Filters out origins which are not associated with the given package-    -- qualifier.  No-op if there is no package qualifier.  Test if this-    -- excluded all origins with 'originEmpty'.-    filterOrigin :: PkgQual-                 -> UnitInfo-                 -> ModuleOrigin-                 -> ModuleOrigin-    filterOrigin NoPkgQual _ o = o-    filterOrigin (ThisPkg _) _ o = o-    filterOrigin (OtherPkg u) pkg o =-      let match_pkg p = u == unitId p-      in case o of-          ModHidden-            | match_pkg pkg -> ModHidden-            | otherwise     -> mempty-          ModUnusable _-            | match_pkg pkg -> o-            | otherwise     -> mempty-          ModOrigin { fromOrigUnit = e, fromExposedReexport = res,-                      fromHiddenReexport = rhs }-            -> ModOrigin-                { fromOrigUnit        = if match_pkg pkg then e else Nothing-                , fromExposedReexport = filter match_pkg res-                , fromHiddenReexport  = filter match_pkg rhs-                , fromPackageFlag     = False -- always excluded-                }--    suggestions = fuzzyLookup (moduleNameString m) all_mods--    all_mods :: [(String, ModuleSuggestion)]     -- All modules-    all_mods = sortBy (comparing fst) $-        [ (moduleNameString m, suggestion)-        | (m, e) <- nonDetUniqMapToList (moduleNameProvidersMap pkgs)-        , suggestion <- map (getSuggestion m) (nonDetUniqMapToList e)-        ]-    getSuggestion name (mod, origin) =-        (if originVisible origin then SuggestVisible else SuggestHidden)-            name mod origin--listVisibleModuleNames :: UnitState -> [ModuleName]-listVisibleModuleNames state =-    map fst (filter visible (nonDetUniqMapToList (moduleNameProvidersMap state)))-  where visible (_, ms) = anyUniqMap originVisible ms---- | Takes a list of UnitIds (and their "parent" dependency, used for error--- messages), and returns the list with dependencies included, in reverse--- dependency order (a units appears before those it depends on).-closeUnitDeps :: UnitInfoMap -> [(UnitId,Maybe UnitId)] -> MaybeErr UnitErr [UnitId]-closeUnitDeps pkg_map ps = closeUnitDeps' pkg_map [] ps---- | Similar to closeUnitDeps but takes a list of already loaded units as an--- additional argument.-closeUnitDeps' :: UnitInfoMap -> [UnitId] -> [(UnitId,Maybe UnitId)] -> MaybeErr UnitErr [UnitId]-closeUnitDeps' pkg_map current_ids ps = foldM (uncurry . add_unit pkg_map) current_ids ps---- | Add a UnitId and those it depends on (recursively) to the given list of--- UnitIds if they are not already in it. Return a list in reverse dependency--- order (a unit appears before those it depends on).------ The UnitId is looked up in the given UnitInfoMap (to find its dependencies).--- It it's not found, the optional parent unit is used to return a more precise--- error message ("dependency of <PARENT>").-add_unit :: UnitInfoMap-            -> [UnitId]-            -> UnitId-            -> Maybe UnitId-            -> MaybeErr UnitErr [UnitId]-add_unit pkg_map ps p mb_parent-  | p `elem` ps = return ps     -- Check if we've already added this unit-  | otherwise   = case lookupUnitId' pkg_map p of-      Nothing   -> Failed (CloseUnitErr p mb_parent)-      Just info -> do-         -- Add the unit's dependents also-         ps' <- foldM add_unit_key ps (unitDepends info)-         return (p : ps')-        where-          add_unit_key xs key-            = add_unit pkg_map xs key (Just p)--data UnitErr-  = CloseUnitErr !UnitId !(Maybe UnitId)-  | PackageFlagErr !PackageFlag ![(UnitInfo,UnusableUnitReason)]-  | TrustFlagErr   !TrustFlag   ![(UnitInfo,UnusableUnitReason)]--mayThrowUnitErr :: MaybeErr UnitErr a -> IO a-mayThrowUnitErr = \case-    Failed e    -> throwGhcExceptionIO-                    $ CmdLineError-                    $ renderWithContext defaultSDocContext-                    $ withPprStyle defaultUserStyle-                    $ ppr e-    Succeeded a -> return a--instance Outputable UnitErr where-    ppr = \case-        CloseUnitErr p mb_parent-            -> (text "unknown unit:" <+> ppr p)-               <> case mb_parent of-                     Nothing     -> Outputable.empty-                     Just parent -> space <> parens (text "dependency of"-                                              <+> ftext (unitIdFS parent))-        PackageFlagErr flag reasons-            -> flag_err (pprFlag flag) reasons--        TrustFlagErr flag reasons-            -> flag_err (pprTrustFlag flag) reasons-      where-        flag_err flag_doc reasons =-            text "cannot satisfy "-            <> flag_doc-            <> (if null reasons then Outputable.empty else text ": ")-            $$ nest 4 (vcat (map ppr_reason reasons) $$-                      text "(use -v for more information)")--        ppr_reason (p, reason) =-            pprReason (ppr (unitId p) <+> text "is") reason---- | Return this list of requirement interfaces that need to be merged--- to form @mod_name@, or @[]@ if this is not a requirement.-requirementMerges :: UnitState -> ModuleName -> [InstantiatedModule]-requirementMerges pkgstate mod_name =-  fromMaybe [] (lookupUniqMap (requirementContext pkgstate) mod_name)---- --------------------------------------------------------------------------------- | Pretty-print a UnitId for the user.------ Cabal packages may contain several components (programs, libraries, etc.).--- As far as GHC is concerned, installed package components ("units") are--- identified by an opaque UnitId string provided by Cabal. As the string--- contains a hash, we don't want to display it to users so GHC queries the--- database to retrieve some infos about the original source package (name,--- version, component name).------ Instead we want to display: packagename-version[:componentname]------ Component name is only displayed if it isn't the default library------ To do this we need to query a unit database.-pprUnitIdForUser :: UnitState -> UnitId -> SDoc-pprUnitIdForUser state uid@(UnitId fs) =-   case lookupUnitPprInfo state uid of-      Nothing -> ftext fs -- we didn't find the unit at all-      Just i  -> ppr i--pprUnitInfoForUser :: UnitInfo -> SDoc-pprUnitInfoForUser info = ppr (mkUnitPprInfo unitIdFS info)--lookupUnitPprInfo :: UnitState -> UnitId -> Maybe UnitPprInfo-lookupUnitPprInfo state uid = fmap (mkUnitPprInfo unitIdFS) (lookupUnitId state uid)---- -------------------------------------------------------------------------------- Displaying packages---- | Show (very verbose) package info-pprUnits :: UnitState -> SDoc-pprUnits = pprUnitsWith pprUnitInfo--pprUnitsWith :: (UnitInfo -> SDoc) -> UnitState -> SDoc-pprUnitsWith pprIPI pkgstate =-    vcat (intersperse (text "---") (map pprIPI (listUnitInfo pkgstate)))---- | Show simplified unit info.------ The idea is to only print package id, and any information that might--- be different from the package databases (exposure, trust)-pprUnitsSimple :: UnitState -> SDoc-pprUnitsSimple = pprUnitsWith pprIPI-    where pprIPI ipi = let i = unitIdFS (unitId ipi)-                           e = if unitIsExposed ipi then text "E" else text " "-                           t = if unitIsTrusted ipi then text "T" else text " "-                       in e <> t <> text "  " <> ftext i---- | Show the mapping of modules to where they come from.-pprModuleMap :: ModuleNameProvidersMap -> SDoc-pprModuleMap mod_map =-  vcat (map pprLine (nonDetUniqMapToList mod_map))-    where-      pprLine (m,e) = ppr m $$ nest 50 (vcat (map (pprEntry m) (nonDetUniqMapToList e)))-      pprEntry :: Outputable a => ModuleName -> (Module, a) -> SDoc-      pprEntry m (m',o)-        | m == moduleName m' = ppr (moduleUnit m') <+> parens (ppr o)-        | otherwise = ppr m' <+> parens (ppr o)--fsPackageName :: UnitInfo -> FastString-fsPackageName info = fs-   where-      PackageName fs = unitPackageName info----- | Given a fully instantiated 'InstantiatedUnit', improve it into a--- 'RealUnit' if we can find it in the package database.-improveUnit :: UnitState -> Unit -> Unit-improveUnit state u = improveUnit' (unitInfoMap state) (preloadClosure state) u---- | Given a fully instantiated 'InstantiatedUnit', improve it into a--- 'RealUnit' if we can find it in the package database.-improveUnit' :: UnitInfoMap -> PreloadUnitClosure -> Unit -> Unit-improveUnit' _       _       uid@(RealUnit _) = uid -- short circuit-improveUnit' pkg_map closure uid =-    -- Do NOT lookup indefinite ones, they won't be useful!-    case lookupUnit' False pkg_map closure uid of-        Nothing  -> uid-        Just pkg ->-            -- Do NOT improve if the indefinite unit id is not-            -- part of the closure unique set.  See-            -- Note [VirtUnit to RealUnit improvement]-            if unitId pkg `elementOfUniqSet` closure-                then mkUnit pkg-                else uid---- | Check the database to see if we already have an installed unit that--- corresponds to the given 'InstantiatedUnit'.------ Return a `UnitId` which either wraps the `InstantiatedUnit` unchanged or--- references a matching installed unit.------ See Note [VirtUnit to RealUnit improvement]-instUnitToUnit :: UnitState -> InstantiatedUnit -> Unit-instUnitToUnit state iuid =-    -- NB: suppose that we want to compare the instantiated-    -- unit p[H=impl:H] against p+abcd (where p+abcd-    -- happens to be the existing, installed version of-    -- p[H=impl:H].  If we *only* wrap in p[H=impl:H]-    -- VirtUnit, they won't compare equal; only-    -- after improvement will the equality hold.-    improveUnit state $ VirtUnit iuid----- | Substitution on module variables, mapping module names to module--- identifiers.-type ShHoleSubst = ModuleNameEnv Module---- | Substitutes holes in a 'Module'.  NOT suitable for being called--- directly on a 'nameModule', see Note [Representation of module/name variables].--- @p[A=\<A>]:B@ maps to @p[A=q():A]:B@ with @A=q():A@;--- similarly, @\<A>@ maps to @q():A@.-renameHoleModule :: UnitState -> ShHoleSubst -> Module -> Module-renameHoleModule state = renameHoleModule' (unitInfoMap state) (preloadClosure state)---- | Substitutes holes in a 'Unit', suitable for renaming when--- an include occurs; see Note [Representation of module/name variables].------ @p[A=\<A>]@ maps to @p[A=\<B>]@ with @A=\<B>@.-renameHoleUnit :: UnitState -> ShHoleSubst -> Unit -> Unit-renameHoleUnit state = renameHoleUnit' (unitInfoMap state) (preloadClosure state)---- | Like 'renameHoleModule', but requires only 'ClosureUnitInfoMap'--- so it can be used by "GHC.Unit.State".-renameHoleModule' :: UnitInfoMap -> PreloadUnitClosure -> ShHoleSubst -> Module -> Module-renameHoleModule' pkg_map closure env m-  | not (isHoleModule m) =-        let uid = renameHoleUnit' pkg_map closure env (moduleUnit m)-        in mkModule uid (moduleName m)-  | Just m' <- lookupUFM env (moduleName m) = m'-  -- NB m = <Blah>, that's what's in scope.-  | otherwise = m---- | Like 'renameHoleUnit, but requires only 'ClosureUnitInfoMap'--- so it can be used by "GHC.Unit.State".-renameHoleUnit' :: UnitInfoMap -> PreloadUnitClosure -> ShHoleSubst -> Unit -> Unit-renameHoleUnit' pkg_map closure env uid =-    case uid of-      (VirtUnit-        InstantiatedUnit{ instUnitInstanceOf = cid-                        , instUnitInsts      = insts-                        , instUnitHoles      = fh })-          -> if isNullUFM (intersectUFM_C const (udfmToUfm (getUniqDSet fh)) env)-                then uid-                -- Functorially apply the substitution to the instantiation,-                -- then check the 'ClosureUnitInfoMap' to see if there is-                -- a compiled version of this 'InstantiatedUnit' we can improve to.-                -- See Note [VirtUnit to RealUnit improvement]-                else improveUnit' pkg_map closure $-                        mkVirtUnit cid-                            (map (\(k,v) -> (k, renameHoleModule' pkg_map closure env v)) insts)-      _ -> uid---- | Injects an 'InstantiatedModule' to 'Module' (see also--- 'instUnitToUnit'.-instModuleToModule :: UnitState -> InstantiatedModule -> Module-instModuleToModule pkgstate (Module iuid mod_name) =-    mkModule (instUnitToUnit pkgstate iuid) mod_name---- | Print unit-ids with UnitInfo found in the given UnitState-pprWithUnitState :: UnitState -> SDoc -> SDoc-pprWithUnitState state = updSDocContext (\ctx -> ctx-   { sdocUnitIdForUser = \fs -> pprUnitIdForUser state (UnitId fs)-   })---- | Print raw unit-ids, without removing the hash-pprRawUnitIds :: SDoc -> SDoc-pprRawUnitIds = updSDocContext (\ctx -> ctx { sdocUnitIdForUser = ftext })+        -- * Reading the package config, and processing cmdline args+        UnitState(..),+        UnitDatabase (..),+        UnitErr (..),+        emptyUnitState,+        initUnits,+        readUnitDatabases,+        readUnitDatabase,+        getUnitDbRefs,+        resolveUnitDatabase,+        listUnitInfo,+        -- * Overlays over the unit set+        TrustOverlay,+        IsTrusted(..),+        lookupTrustOverlay,+        distrustUnits,+        trustUnits,+        emptyTrustOverlay,+        -- * Querying the package config+        lookupUnit,+        lookupUnit',+        unsafeLookupUnit,+        lookupUnitId,+        lookupUnitId',+        unsafeLookupUnitId,+        isUnitTrusted,+        isUnitIdTrusted,+        isUnitInfoTrusted,++        lookupPackageName,+        resolvePackageImport,+        searchPackageId,+        listVisibleModuleNames,+        lookupModuleInAllUnits,+        lookupModuleWithSuggestions,+        lookupModulePackage,+        lookupPluginModuleWithSuggestions,+        requirementMerges,+        LookupResult(..),+        ModuleSuggestion(..),+        ModuleOrigin(..),+        UnusableUnit(..),+        UnusableUnitReason(..),+        pprReason,++        closeUnitDeps,+        closeUnitDeps',+        mayThrowUnitErr,++        -- * Module hole substitution+        ShHoleSubst,+        renameHoleUnit,+        renameHoleModule,+        renameHoleUnit',+        renameHoleModule',+        instUnitToUnit,+        instModuleToModule,++        -- * Pretty-printing+        pprFlag,+        pprUnits,+        pprUnitsSimple,+        pprUnitIdForUser,+        pprUnitInfoForUser,+        pprModuleMap,+        pprWithUnitState,+        pprRawUnitIds,++        -- * Utils+        unwireUnit,+        selectHptFlag,+        )+where++import GHC.Prelude++import GHC.Driver.DynFlags++import GHC.Platform+import GHC.Platform.Ways++import GHC.Unit.Database+import GHC.Unit.Home+import GHC.Unit.Info+import GHC.Unit.Module+import GHC.Unit.Ppr++import GHC.Unit.External.Database+import GHC.Unit.External.Index+import GHC.Unit.External.ModuleOrigin+import GHC.Unit.External.Providers+import GHC.Unit.External.Query+import GHC.Unit.External.Substitution+import GHC.Unit.External.Validate+import GHC.Unit.External.Visibility+import GHC.Unit.External.Wired++import GHC.Types.PkgQual+import GHC.Types.Unique.DFM+import GHC.Types.Unique.FM+import GHC.Types.Unique.Map++import GHC.Data.Maybe+import GHC.Utils.Misc+import GHC.Utils.Outputable as Outputable+import GHC.Utils.Panic++import GHC.Data.FastString+import GHC.Data.OsPath qualified as OsPath+import GHC.Data.ShortText qualified as ST+import GHC.Utils.Error+import GHC.Utils.Logger++import Control.Monad+import Data.Graph (SCC (..))+import Data.List (intersperse, partition, sortOn)+import Data.Monoid (First (..))+import Data.Set (Set)+import Data.Set qualified as Set++-- ---------------------------------------------------------------------------+-- The Unit state++-- The unit state is computed by 'initUnits', and kept in HscEnv.+-- It is influenced by various command-line flags:+--+--   * @-package \<pkg>@ and @-package-id \<pkg>@ cause @\<pkg>@ to become exposed.+--     If @-hide-all-packages@ was not specified, these commands also cause+--      all other packages with the same name to become hidden.+--+--   * @-hide-package \<pkg>@ causes @\<pkg>@ to become hidden.+--+--   * (there are a few more flags, check below for their semantics)+--+-- The unit state has the following properties.+--+--   * Let @exposedUnits@ be the set of packages thus exposed.+--     Let @depExposedUnits@ be the transitive closure from @exposedUnits@ of+--     their dependencies.+--+--   * When searching for a module from a preload import declaration,+--     only the exposed modules in @exposedUnits@ are valid.+--+--   * When searching for a module from an implicit import, all modules+--     from @depExposedUnits@ are valid.+--+--   * When linking in a compilation manager mode, we link in packages the+--     program depends on (the compiler knows this list by the+--     time it gets to the link step).  Also, we link in all packages+--     which were mentioned with preload @-package@ flags on the command-line,+--     or are a transitive dependency of same, or are \"base\"\/\"rts\".+--     The reason for this is that we might need packages which don't+--     contain any Haskell modules, and therefore won't be discovered+--     by the normal mechanism of dependency tracking.++-- Notes on DLLs+-- ~~~~~~~~~~~~~+-- When compiling module A, which imports module B, we need to+-- know whether B will be in the same DLL as A.+--      If it's in the same DLL, we refer to B_f_closure+--      If it isn't, we refer to _imp__B_f_closure+-- When compiling A, we record in B's Module value whether it's+-- in a different DLL, by setting the DLL flag.++-- | Unit configuration+data UnitConfig = UnitConfig+   { unitConfigPlatformArchOS :: !ArchOS        -- ^ Platform arch and OS+   , unitConfigWays           :: !Ways          -- ^ Ways to use++   , unitConfigAllowVirtual   :: !Bool          -- ^ Allow virtual units+      -- ^ Do we allow the use of virtual units instantiated on-the-fly (see+      -- Note [About units] in GHC.Unit). This should only be true when we are+      -- type-checking an indefinite unit (not producing any code).++   , unitConfigProgramName    :: !String+      -- ^ Name of the compiler (e.g. "GHC", "GHCJS"). Used to fetch environment+      -- variables such as "GHC[JS]_PACKAGE_PATH".++   , unitConfigGlobalDB :: !FilePath    -- ^ Path to global DB+   , unitConfigGHCDir   :: !FilePath    -- ^ Main GHC dir: contains settings, etc.+   , unitConfigDBName   :: !String      -- ^ User DB name (e.g. "package.conf.d")++   , unitConfigAutoLink       :: ![UnitId] -- ^ Units to link automatically (e.g. base, rts)+   , unitConfigDistrustAll    :: !Bool     -- ^ Distrust all units by default+   , unitConfigHideAll        :: !Bool     -- ^ Hide all units by default+   , unitConfigHideAllPlugins :: !Bool     -- ^ Hide all plugins units by default++   -- command-line flags+   , unitConfigFlagsDB      :: [PackageDBFlag]     -- ^ Unit databases flags+   , unitConfigFlagsExposed :: [PackageFlag]       -- ^ Exposed units+   , unitConfigFlagsIgnored :: [IgnorePackageFlag] -- ^ Ignored units+   , unitConfigFlagsTrusted :: [TrustFlag]         -- ^ Trusted units+   , unitConfigFlagsPlugins :: [PackageFlag]       -- ^ Plugins exposed units+   , unitConfigHomeUnits    :: Set.Set UnitId+   }++initUnitConfig :: DynFlags -> Set.Set UnitId -> UnitConfig+initUnitConfig dflags home_units =+   let !hu_id             = homeUnitId_ dflags+       !hu_instanceof     = homeUnitInstanceOf_ dflags+       !hu_instantiations = homeUnitInstantiations_ dflags++       autoLink+         | not (gopt Opt_AutoLinkPackages dflags) = []+         -- By default we add base, ghc-internal and rts to the preload units (when they are+         -- found in the unit database) except when we are building them+         --+         -- Since "base" is not wired in, then the unit-id is discovered+         -- from the settings file by default, but can be overriden by power-users+         -- by specifying `-base-unit-id` flag.+         | otherwise = filter (hu_id /=) [baseUnitId dflags, ghcInternalUnitId, rtsUnitId]++       -- if the home unit is indefinite, it means we are type-checking it only+       -- (not producing any code). Hence we can use virtual units instantiated+       -- on-the-fly. See Note [About units] in GHC.Unit+       allow_virtual_units = case (hu_instanceof, hu_instantiations) of+            (Just u, is) -> u == hu_id && any (isHoleModule . snd) is+            _            -> False++   in UnitConfig+      { unitConfigPlatformArchOS = platformArchOS (targetPlatform dflags)+      , unitConfigProgramName    = programName dflags+      , unitConfigWays           = ways dflags+      , unitConfigAllowVirtual   = allow_virtual_units++      , unitConfigGlobalDB       = globalPackageDatabasePath dflags+      , unitConfigGHCDir         = topDir dflags+      , unitConfigDBName         = "package.conf.d"++      , unitConfigAutoLink       = autoLink+      , unitConfigDistrustAll    = gopt Opt_DistrustAllPackages dflags+      , unitConfigHideAll        = gopt Opt_HideAllPackages dflags+      , unitConfigHideAllPlugins = gopt Opt_HideAllPluginPackages dflags++      , unitConfigFlagsDB      = map (offsetPackageDb (workingDirectory dflags)) $ packageDBFlags dflags+      , unitConfigFlagsExposed = packageFlags dflags+      , unitConfigFlagsIgnored = ignorePackageFlags dflags+      , unitConfigFlagsTrusted = trustFlags dflags+      , unitConfigFlagsPlugins = pluginPackageFlags dflags+      , unitConfigHomeUnits    = home_units++      }++  where+    offsetPackageDb :: Maybe FilePath -> PackageDBFlag -> PackageDBFlag+    offsetPackageDb (Just offset) (PackageDB (PkgDbPath p)) | OsPath.isRelative p = PackageDB (PkgDbPath (OsPath.unsafeEncodeUtf offset OsPath.</> p))+    offsetPackageDb _ p = p++data IsTrusted+  = Trusted+  | Distrusted+  deriving ( Eq, Ord )++-- | The 'TrustOverlay' stores user overwrites of the on-disk 'unitIsTrusted' status.+--+-- The user can overwrite this value via flags such as @-distrust-all-packages@.+-- We do not modify the 'UnitInfo' directory, but rather store this user selection+-- in the 'TrustOverlay'.+--+-- This allows us to share the 'UnitInfo' completely and saves us memory.+newtype TrustOverlay = TrustOverlay+  { trustOverlay :: UniqMap UnitId IsTrusted+  }++lookupTrustOverlay :: TrustOverlay -> UnitId -> Maybe IsTrusted+lookupTrustOverlay to = lookupUniqMap (trustOverlay to)++distrustUnits :: [UnitId] -> TrustOverlay -> TrustOverlay+distrustUnits elements (TrustOverlay to) = TrustOverlay $ foldl' (\ acc uid -> addToUniqMap acc uid Distrusted) to elements++trustUnits :: [UnitId] -> TrustOverlay -> TrustOverlay+trustUnits elements (TrustOverlay to) = TrustOverlay $ foldl' (\ acc uid -> addToUniqMap acc uid Trusted) to elements++emptyTrustOverlay :: TrustOverlay+emptyTrustOverlay = TrustOverlay emptyUniqMap++-- | For all values in the 'WireMap', copy the recorded trust/distrust+-- for the wired-in unit id.+--+extendForWireMap :: TrustOverlay -> WireMap -> TrustOverlay+extendForWireMap to wmap =+  nonDetFoldWireMap go to wmap+  where+    go (onDiskUid, wiredInUid) overlay =+      case lookupTrustOverlay overlay onDiskUid of+        Nothing -> overlay+        Just Trusted ->+          trustUnits [wiredInUid] overlay+        Just Distrusted ->+          distrustUnits [wiredInUid] overlay++{-+Note [Sharing 'UnitInfo's across the 'UnitEnv']+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+The 'UnitState' and 'UnitIndex' are closely related.++The 'UnitState' stores all information about the external units referenced by+a single 'HomeUnitEnv'.+As a reminder, the 'HomeUnitEnv' stores all information specific to a single home unit,+such as the 'HomePackageTable', 'DynFlags' and the 'UnitState'.+The 'UnitState' retains the 'unitInfoMap', an in-memory representation of+the unit databases that a 'HomeUnitEnv' depends on.+Multiple home units can depend on the same unit database, and reference the same+'UnitInfo's across the GHC session.+We share all 'UnitInfo's across multiple 'HomeUnitEnv's, saving a lot of+duplication of the same 'UnitInfo'.+This what the 'UnitIndex' takes care of.++The 'UnitIndex' stores all fully-resolved 'UnitInfo's that can be referenced+by the 'UnitState'.'unitInfoMap'.+We consider a 'UnitInfo' as fully-resolved, if its dependencies were updated to reference the+wired-in units (e.g., 'wiringMap') and the wired-in units are updated as well.+See Note [Wired-in units] for more details on wired-in units.+Further, the 'UnitInfo' is based on the 'ExternalUnitDatabases' results, resolving+variables such as @${pkgroot}@ in paths.++As such, we can consider the 'UnitIndex' to be global data that is referenced by+the 'UnitState' for better sharing of 'UnitInfo's.++In fact, using the 'UnitIndex', we can impose a hard upper bound on the number+of live 'UnitInfo's in a GHC session:++> For each on-disk 'GenericUnitInfo', there are at most two objects alive.++One instance is stored in 'ExternalUnitDatabases' where variables are resolved,+but the wired-in units haven't been resolved.++The second instance is the fully-resolved 'UnitInfo' stored in the 'UnitIndex'.++See the module documentation for 'GHC.Unit.External.Index' for an overview+of how the types relate to each other.+-}++-- | The 'UnitState' contains a plethora of information local to a single 'HomeUnitEnv'.+--+-- It stores module visibilities, unit trust for @SafeHaskell@, available units for error messages,+-- explicit unit dependencies and knows how to instantiate backpack signature and holes+-- on demand.+--+-- A 'HomeUnitEnv' should rarely/never have to look into the 'UnitIndex', all external+-- unit related information is stored in the 'UnitState'.+--+data UnitState = UnitState {+  -- | A mapping of 'Unit' to 'UnitInfo'.  This list is adjusted+  -- so that only valid units are here.  'UnitInfo' reflects+  -- what was stored *on disk*, except for the 'trusted' flag, which+  -- is adjusted at runtime.  (In particular, some units in this map+  -- may have the 'exposed' flag be 'False'.)+  --+  -- All values are shared with 'UnitIndex'.'globalUnits'.+  -- See Note [Sharing 'UnitInfo's across the 'UnitEnv'] for details.+  unitInfoMap :: UnitInfoMap,++  -- | Set of units that we trust.+  --+  -- Local overlay of 'UnitInfo'.+  -- This avoids modifying the 'UnitInfo' directly, potentially saving+  -- a lot of duplication.+  --+  -- We keep this in WHNF as it is relatively cheap but could easily retain+  -- references to bigger structures.+  trustedUnits :: !TrustOverlay,++  -- | A mapping of 'PackageName' to 'UnitId'. If several units have the same+  -- package name (e.g. different instantiations), then we return one of them...+  -- This is used when users refer to packages in Backpack includes.+  -- And also to resolve package qualifiers with the PackageImports extension.+  packageNameMap            :: UniqFM PackageName UnitId,++  -- | The units we're going to link in eagerly.  This list+  -- should be in reverse dependency order; that is, a unit+  -- is always mentioned before the units it depends on.+  preloadUnits      :: [UnitId],++  -- | Units which we explicitly depend on (from a command line flag).+  -- We'll use this to generate version macros and the unused packages warning. The+  -- original flag which was used to bring the unit into scope is recorded for the+  -- -Wunused-packages warning.+  explicitUnits :: [(Unit, Maybe PackageArg)],++  homeUnitDepends    :: Set UnitId,++  -- | This is a full map from 'ModuleName' to all modules which may possibly+  -- be providing it.  These providers may be hidden (but we'll still want+  -- to report them in error messages), or it may be an ambiguous import.+  moduleNameProvidersMap    :: !ModuleNameProvidersMap,++  -- | A map, like 'moduleNameProvidersMap', but controlling plugin visibility.+  pluginModuleNameProvidersMap    :: !ModuleNameProvidersMap,++  -- | A map saying, for each requirement, what interfaces must be merged+  -- together when we use them.  For example, if our dependencies+  -- are @p[A=\<A>]@ and @q[A=\<A>,B=r[C=\<A>]:B]@, then the interfaces+  -- to merge for A are @p[A=\<A>]:A@, @q[A=\<A>,B=r[C=\<A>]:B]:A@+  -- and @r[C=\<A>]:C@.+  --+  -- There's an entry in this map for each hole in our home library.+  requirementContext :: UniqMap ModuleName [InstantiatedModule],++  -- | Indicate if we can instantiate units on-the-fly.+  --+  -- This should only be true when we are type-checking an indefinite unit.+  -- See Note [About units] in GHC.Unit.+  allowVirtualUnits :: !Bool+  }++emptyUnitState :: UnitState+emptyUnitState = UnitState {+    unitInfoMap    = emptyUniqMap,+    trustedUnits   = emptyTrustOverlay,+    packageNameMap = emptyUFM,+    preloadUnits   = [],+    explicitUnits  = [],+    homeUnitDepends = Set.empty,+    moduleNameProvidersMap       = emptyUniqMap,+    pluginModuleNameProvidersMap = emptyUniqMap,+    requirementContext           = emptyUniqMap,+    allowVirtualUnits = False+    }++-- | Find the unit we know about with the given unit, if any+lookupUnit :: UnitState -> Unit -> Maybe UnitInfo+lookupUnit pkgs = lookupUnit' (allowVirtualUnits pkgs) (unitInfoMap pkgs)++-- | Find the unit we know about with the given unit id, if any+lookupUnitId :: UnitState -> UnitId -> Maybe UnitInfo+lookupUnitId state uid = lookupUnitId' (unitInfoMap state) uid++-- | Looks up the given unit in the unit state, panicking if it is not found+unsafeLookupUnit :: HasDebugCallStack => UnitState -> Unit -> UnitInfo+unsafeLookupUnit state u = case lookupUnit state u of+   Just info -> info+   Nothing   -> pprPanic "unsafeLookupUnit" (ppr u)++-- | Looks up the given unit id in the unit state, panicking if it is not found+unsafeLookupUnitId :: HasDebugCallStack => UnitState -> UnitId -> UnitInfo+unsafeLookupUnitId state uid = case lookupUnitId state uid of+   Just info -> info+   Nothing   -> pprPanic "unsafeLookupUnitId" (ppr uid)+++-- | Find the unit we know about with the given package name (e.g. @foo@), if any+-- (NB: there might be a locally defined unit name which overrides this)+-- This function is unsafe to use in general because it doesn't respect package+-- visibility.+lookupPackageName :: UnitState -> PackageName -> Maybe UnitId+lookupPackageName pkgstate n = lookupUFM (packageNameMap pkgstate) n++-- | Search for units with a given package ID (e.g. \"foo-0.1\")+searchPackageId :: UnitState -> PackageId -> [UnitInfo]+searchPackageId pkgstate pid = filter ((pid ==) . unitPackageId)+                               (listUnitInfo pkgstate)++-- | Find the UnitId which an import qualified by a package import comes from.+-- Compared to 'lookupPackageName', this function correctly accounts for visibility,+-- renaming and thinning.+resolvePackageImport :: UnitState -> ModuleName -> PackageName -> Maybe UnitId+resolvePackageImport unit_st mn pn = do+  -- 1. Find all modules providing the ModuleName (this accounts for visibility/thinning etc)+  providers <- filterUniqMap originVisible <$> lookupUniqMap (moduleNameProvidersMap unit_st) mn+  -- 2. Get the UnitIds of the candidates+  let candidates_uid = concatMap to_uid $ sortOn fst $ nonDetUniqMapToList providers+  -- 3. Get the package names of the candidates+  let candidates_units = map (\ui -> ((unitPackageName ui), unitId ui))+                              $ mapMaybe (\uid -> lookupUniqMap (unitInfoMap unit_st) uid) candidates_uid+  -- 4. Check to see if the PackageName helps us disambiguate any candidates.+  lookup pn candidates_units++  where++    -- Get the UnitId from which a visible identifier is from+    to_uid :: (Module, ModuleOrigin) -> [UnitId]+    to_uid (mod, ModOrigin mo re_exps _ _) =+      case mo of+        -- Available directly, but also potentially from re-exports+        Just True ->  (toUnitId (moduleUnit mod)) : map unitId re_exps+        -- Just available from these re-exports+        _ -> map unitId re_exps+    to_uid _ = []++-- | Get a list of entries from the unit database.  NB: be careful with+-- this function, although all units in this map are "visible", this+-- does not imply that the exposed-modules of the unit are available+-- (they may have been thinned or renamed).+listUnitInfo :: UnitState -> [UnitInfo]+listUnitInfo state = nonDetEltsUniqMap (unitInfoMap state)++-- | Do we trust the 'UnitInfo' for the given 'UnitId'?+isUnitIdTrusted :: HasDebugCallStack => UnitState -> UnitId -> Bool+isUnitIdTrusted ue u =+    case lookupTrustOverlay (trustedUnits ue) u of+      Just Trusted -> True+      Just Distrusted -> False+      Nothing -> unitIsTrusted (unsafeLookupUnitId ue u) -- No overlay for this unit, check the on-disk value++-- | Do we trust the 'UnitInfo' for the given 'Unit'?+isUnitTrusted :: HasDebugCallStack => UnitState -> Unit -> Bool+isUnitTrusted ue u =+  isUnitIdTrusted ue (toUnitId u)++-- | Do we trust the given 'UnitInfo'?+isUnitInfoTrusted :: HasDebugCallStack => UnitState -> UnitInfo -> Bool+isUnitInfoTrusted ue u =+  isUnitIdTrusted ue (unitId u)++-- ----------------------------------------------------------------------------+-- Loading the unit db files and building up the unit state++-- | Read the unit database files, and sets up various internal tables of+-- unit information, according to the unit-related flags on the+-- command-line (@-package@, @-hide-package@ etc.)+--+-- 'initUnits' can be called again subsequently after updating the+-- 'packageFlags' and 'packageDBFlags' fields of the 'DynFlags', and it will+-- update the 'unitState' in 'DynFlags'.+--+-- Also, see Note [Sharing 'UnitInfo's across the 'UnitEnv'] for implementation details.+initUnits :: Logger -> DynFlags -> UnitIndexCache -> Set.Set UnitId -> IO (UnitState, HomeUnit, Maybe PlatformConstants)+initUnits logger dflags unit_index home_units = do++  let forceUnitInfoMap state = unitInfoMap state `seq` ()++  unit_state <- withTiming logger (text "initializing unit database")+                   forceUnitInfoMap+                 $ mkUnitState logger unit_index (initUnitConfig dflags  home_units)++  putDumpFileMaybe logger Opt_D_dump_mod_map "Module Map"+    FormatText (updSDocContext (\ctx -> ctx {sdocLineLength = 200})+                $ pprModuleMap (moduleNameProvidersMap unit_state))++  wireMap <- wiringMap <$> readUnitIndex unit_index++  let home_unit = mkHomeUnit wireMap+                             (homeUnitId_ dflags)+                             (homeUnitInstanceOf_ dflags)+                             (homeUnitInstantiations_ dflags)++  -- Try to find platform constants+  --+  -- See Note [Platform constants] in GHC.Platform+  mconstants <- if homeUnitId_ dflags == rtsUnitId+    then do+      -- we're building the RTS! Lookup DerivedConstants.h in the include paths+      lookupPlatformConstants (includePathsGlobal (includePaths dflags))+    else+      -- lookup the DerivedConstants.h header bundled with the RTS unit. We+      -- don't fail if we can't find the RTS unit as it can be a valid (but+      -- uncommon) case, e.g. building a C utility program (not depending on the+      -- RTS) before building the RTS. In any case, we will fail later on if we+      -- really need to use the platform constants but they have not been loaded.+      case lookupUnitId unit_state rtsUnitId of+        Nothing   -> return Nothing+        Just info -> lookupPlatformConstants (fmap ST.unpack (unitIncludeDirs info))++  return (unit_state,home_unit,mconstants)++mkHomeUnit+    :: WireMap+    -> UnitId                 -- ^ Home unit id+    -> Maybe UnitId           -- ^ Home unit instance of+    -> [(ModuleName, Module)] -- ^ Home unit instantiations+    -> HomeUnit+mkHomeUnit wmap hu_id hu_instanceof hu_instantiations_ =+    let+        -- Some wired units can be used to instantiate the home unit. We need to+        -- replace their unit keys with their wired unit ids.+        hu_instantiations = map (fmap (updateWiredInUnitIdInModule wmap)) hu_instantiations_+    in case (hu_instanceof, hu_instantiations) of+      (Nothing,[]) -> DefiniteHomeUnit hu_id Nothing+      (Nothing, _) -> throwGhcException $ CmdLineError ("Use of -instantiated-with requires -this-component-id")+      (Just _, []) -> throwGhcException $ CmdLineError ("Use of -this-component-id requires -instantiated-with")+      (Just u, is)+         -- detect fully indefinite units: all their instantiations are hole+         -- modules and the home unit id is the same as the instantiating unit+         -- id (see Note [About units] in GHC.Unit)+         | all (isHoleModule . snd) is && u == hu_id+         -> IndefiniteHomeUnit u is+         -- otherwise it must be that we (fully) instantiate an indefinite unit+         -- to make it definite.+         -- TODO: error when the unit is partially instantiated??+         | otherwise+         -> DefiniteHomeUnit hu_id (Just (u, is))++-- -----------------------------------------------------------------------------+-- Modify our copy of the unit database based on trust flags,+-- -trust and -distrust.++applyTrustFlag+   :: UnitPrecedenceMap+   -> UnusableUnits+   -> [UnitInfo]+   -> TrustOverlay+   -> TrustFlag+   -> MaybeErr UnitErr TrustOverlay+applyTrustFlag prec_map unusable pkgs overlay flag =+  case flag of+    -- we trust all matching packages. Maybe should only trust first one?+    -- and leave others the same or set them untrusted+    TrustPackage str ->+       case selectPackages prec_map (PackageArg str) pkgs unusable of+         Left ps       -> Failed (TrustFlagErr flag ps)+         Right (ps,_) -> Succeeded (trustUnits (map unitId ps) overlay)++    DistrustPackage str ->+       case selectPackages prec_map (PackageArg str) pkgs unusable of+         Left ps       -> Failed (TrustFlagErr flag ps)+         Right (ps,_) -> Succeeded (distrustUnits (map unitId ps) overlay)++applyPackageFlag+   :: UnitPrecedenceMap+   -> UnitInfoMap+   -> UnusableUnits+   -> Bool -- if False, if you expose a package, it implicitly hides+           -- any previously exposed packages with the same name+   -> [UnitInfo]+   -> VisibilityMap           -- Initially exposed+   -> PackageFlag             -- flag to apply+   -> MaybeErr UnitErr VisibilityMap -- Now exposed++applyPackageFlag prec_map pkg_map unusable no_hide_others pkgs vm flag =+  case flag of+    ExposePackage _ arg (ModRenaming b rns) ->+       case findPackages prec_map pkg_map arg pkgs unusable of+         Left ps     -> Failed (PackageFlagErr flag ps)+         Right (p:_) -> Succeeded vm'+          where+           n = fsPackageName p++           -- If a user says @-unit-id p[A=<A>]@, this imposes+           -- a requirement on us: whatever our signature A is,+           -- it must fulfill all of p[A=<A>]:A's requirements.+           -- This method is responsible for computing what our+           -- inherited requirements are.+           reqs | UnitIdArg orig_uid <- arg = collectHoles orig_uid+                | otherwise                 = emptyUniqMap++           collectHoles uid = case uid of+             HoleUnit       -> emptyUniqMap+             RealUnit {}    -> emptyUniqMap -- definite units don't have holes+             VirtUnit indef ->+                  let local = [ unitUniqMap+                                  (moduleName mod)+                                  (Set.singleton $ Module indef mod_name)+                              | (mod_name, mod) <- instUnitInsts indef+                              , isHoleModule mod ]+                      recurse = [ collectHoles (moduleUnit mod)+                                | (_, mod) <- instUnitInsts indef ]+                  in plusUniqMapListWith Set.union $ local ++ recurse++           uv = UnitVisibility+                { uv_expose_all = b+                , uv_renamings = rns+                , uv_package_name = First (Just n)+                , uv_requirements = reqs+                , uv_explicit = Just arg+                }+           vm' = addToUniqMap_C mappend vm_cleared (mkUnit p) uv+           -- In the old days, if you said `ghc -package p-0.1 -package p-0.2`+           -- (or if p-0.1 was registered in the pkgdb as exposed: True),+           -- the second package flag would override the first one and you+           -- would only see p-0.2 in exposed modules.  This is good for+           -- usability.+           --+           -- However, with thinning and renaming (or Backpack), there might be+           -- situations where you legitimately want to see two versions of a+           -- package at the same time, and this behavior would make it+           -- impossible to do so.  So we decided that if you pass+           -- -hide-all-packages, this should turn OFF the overriding behavior+           -- where an exposed package hides all other packages with the same+           -- name.  This should not affect Cabal at all, which only ever+           -- exposes one package at a time.+           --+           -- NB: Why a variable no_hide_others?  We have to apply this logic to+           -- -plugin-package too, and it's more consistent if the switch in+           -- behavior is based off of+           -- -hide-all-packages/-hide-all-plugin-packages depending on what+           -- flag is in question.+           vm_cleared | no_hide_others = vm+                      -- NB: renamings never clear+                      | (_:_) <- rns = vm+                      | otherwise = filterWithKeyUniqMap+                            (\k uv -> k == mkUnit p+                                   || First (Just n) /= uv_package_name uv) vm+         _ -> panic "applyPackageFlag"++    HidePackage str ->+       case findPackages prec_map pkg_map (PackageArg str) pkgs unusable of+         Left ps  -> Failed (PackageFlagErr flag ps)+         Right ps -> Succeeded $ foldl' delFromUniqMap vm (map mkUnit ps)++updateVisibilityMap :: WireMap -> VisibilityMap -> VisibilityMap+updateVisibilityMap wiredInMap vis_map = foldl' f vis_map (listWireMap wiredInMap)+  where f vm (from, to) = case lookupUniqMap vis_map (RealUnit (Definite from)) of+                    Nothing -> vm+                    Just r -> addToUniqMap (delFromUniqMap vm (RealUnit (Definite from)))+                              (RealUnit (Definite to)) r++  -- ----------------------------------------------------------------------------++reportCycles :: Logger -> [SCC UnitInfo] -> IO ()+reportCycles logger sccs = mapM_ report sccs+  where+    report (AcyclicSCC _) = return ()+    report (CyclicSCC vs) =+        debugTraceMsg logger 2 $+          text "these packages are involved in a cycle:" $$+            nest 2 (hsep (map (ppr . unitId) vs))+++-- -----------------------------------------------------------------------------+-- When all the command-line options are in, we can process our unit+-- settings and populate the unit state.++mkUnitState+    :: Logger+    -> UnitIndexCache+    -> UnitConfig+    -> IO UnitState+mkUnitState logger unit_index cfg = do+{-+   Plan.++   There are two main steps for making the package state:++    1. We want to build a single, unified package database based+       on all of the input databases, which upholds the invariant that+       there is only one package per any UnitId and there are no+       dangling dependencies.  We'll do this by merging, and+       then successively filtering out bad dependencies.++       a) Merge all the databases together.+          If an input database defines unit ID that is already in+          the unified database, that package SHADOWS the existing+          package in the current unified database.  Note that+          order is important: packages defined later in the list of+          command line arguments shadow those defined earlier.++       b) Remove all packages with missing dependencies, or+          mutually recursive dependencies.++       b) Remove packages selected by -ignore-package from input database++       c) Remove all packages which depended on packages that are now+          shadowed by an ABI-incompatible package++       d) report (with -v) any packages that were removed by steps 1-3++    2. We want to look at the flags controlling package visibility,+       and build a mapping of what module names are in scope and+       where they live.++       a) on the final, unified database, we apply -trust/-distrust+          flags directly, modifying the database so that the 'trusted'+          field has the correct value.++       b) we use the -package/-hide-package flags to compute a+          visibility map, stating what packages are "exposed" for+          the purposes of computing the module map.+          * if any flag refers to a package which was removed by 1-5, then+            we can give an error message explaining why+          * if -hide-all-packages was not specified, this step also+            hides packages which are superseded by later exposed packages+          * this step is done TWICE if -plugin-package/-hide-all-plugin-packages+            are used++       c) based on the visibility map, we pick wired packages and rewrite+          them to have the expected unitId.++       d) finally, using the visibility map and the package database,+          we build a mapping saying what every in scope module name points to.+-}++  dbs <- readUnitDatabases logger unit_index (initUnitDbConfig cfg)++  -- distrust all units if the flag is set+  let distrustUnitsOfDb overlay db = foldl' (\ acc ui -> distrustUnits [unitId ui] acc) overlay (unitDatabaseUnits db)+      distrustAllUnits = foldl' distrustUnitsOfDb emptyTrustOverlay dbs++      distrustedUnitsOverlay+        | unitConfigDistrustAll cfg = distrustAllUnits+        | otherwise = emptyTrustOverlay++  -- This, and the other reverse's that you will see, are due to the fact that+  -- packageFlags, pluginPackageFlags, etc. are all specified in *reverse* order+  -- than they are on the command line.+  let raw_other_flags = reverse (unitConfigFlagsExposed cfg)+      (hpt_flags, other_flags) = partition (selectHptFlag (unitConfigHomeUnits cfg)) raw_other_flags+  debugTraceMsg logger 2 $+      text "package flags" <+> ppr other_flags++  let home_unit_deps = selectHomeUnits (unitConfigHomeUnits cfg) hpt_flags++  -- Merge databases together, without checking validity+  (pkg_map1, prec_map) <- mergeDatabases logger dbs++  -- Now that we've merged everything together, prune out unusable+  -- packages.+  let (pkg_map2, unusable, sccs) = validateDatabase (unitConfigFlagsIgnored cfg) pkg_map1++  reportCycles   logger sccs+  reportUnusable logger unusable++  -- Compute trust flags (these flags apply regardless of whether+  -- or not packages are visible or not)+  trustUnitsOverlay <- mayThrowUnitErr+            $ foldM (applyTrustFlag prec_map unusable (nonDetEltsUniqMap pkg_map2))+                 distrustedUnitsOverlay (reverse (unitConfigFlagsTrusted cfg))+  let pkgs1 = nonDetEltsUniqMap pkg_map2+  let prelim_pkg_db = mkUnitInfoMap pkgs1++  --+  -- Calculate the initial set of units from package databases, prior to any package flags.+  --+  -- Conceptually, we select the latest versions of all valid (not unusable) *packages*+  -- (not units). This is empty if we have -hide-all-packages.+  --+  -- Then we create an initial visibility map with default visibilities for all+  -- exposed, definite units which belong to the latest valid packages.+  --+  let preferLater unit unit' =+        case compareByPreference prec_map unit unit' of+            GT -> unit+            _  -> unit'+      addIfMorePreferable m unit = addToUDFM_C preferLater m (fsPackageName unit) unit+      -- This is the set of maximally preferable packages. In fact, it is a set of+      -- most preferable *units* keyed by package name, which act as stand-ins in+      -- for "a package in a database". We use units here because we don't have+      -- "a package in a database" as a type currently.+      mostPreferablePackageReps = if unitConfigHideAll cfg+                    then emptyUDFM+                    else foldl' addIfMorePreferable emptyUDFM pkgs1+      -- When exposing units, we want to consider all of those in the most preferable+      -- packages. We can implement that by looking for units that are equi-preferable+      -- with the most preferable unit for package. Being equi-preferable means that+      -- they must be in the same database, with the same version, and the same package name.+      --+      -- We must take care to consider all these units and not just the most+      -- preferable one, otherwise we can end up with problems like #16228.+      mostPreferable u =+        case lookupUDFM mostPreferablePackageReps (fsPackageName u) of+          Nothing -> False+          Just u' -> compareByPreference prec_map u u' == EQ+      vis_map1 = foldl' (\vm p ->+                            -- Note: we NEVER expose indefinite packages by+                            -- default, because it's almost assuredly not+                            -- what you want (no mix-in linking has occurred).+                            if unitIsExposed p && unitIsDefinite (mkUnit p) && mostPreferable p+                               then addToUniqMap vm (mkUnit p)+                                               UnitVisibility {+                                                 uv_expose_all = True,+                                                 uv_renamings = [],+                                                 uv_package_name = First (Just $ fsPackageName p),+                                                 uv_requirements = emptyUniqMap,+                                                 uv_explicit = Nothing+                                               }+                               else vm)+                         emptyUniqMap pkgs1++  --+  -- Compute a visibility map according to the command-line flags (-package,+  -- -hide-package).  This needs to know about the unusable packages, since if a+  -- user tries to enable an unusable package, we should let them know.+  --+  vis_map2 <- mayThrowUnitErr+                $ foldM (applyPackageFlag prec_map prelim_pkg_db unusable+                        (unitConfigHideAll cfg) pkgs1)+                            vis_map1 other_flags++  --+  -- Sort out which packages are wired in. This has to be done last, since+  -- it modifies the unit ids of wired in packages, but when we process+  -- package arguments we need to key against the old versions.+  --+  wired_map <- setupWiredInUnits logger prec_map pkgs1 vis_map2 unit_index+  pkgs2 <- updateWiredInUnitIndex wired_map pkgs1 unit_index++  let pkg_db = mkUnitInfoMap pkgs2++  -- Update the visibility map, so we treat wired packages as visible.+  let vis_map = updateVisibilityMap wired_map vis_map2++  let hide_plugin_pkgs = unitConfigHideAllPlugins cfg+  plugin_vis_map <-+    case unitConfigFlagsPlugins cfg of+        -- common case; try to share the old vis_map+        [] | not hide_plugin_pkgs -> return vis_map+           | otherwise -> return emptyUniqMap+        _ -> do let plugin_vis_map1+                        | hide_plugin_pkgs = emptyUniqMap+                        -- Use the vis_map PRIOR to wired in,+                        -- because otherwise applyPackageFlag+                        -- won't work.+                        | otherwise = vis_map2+                plugin_vis_map2+                    <- mayThrowUnitErr+                        $ foldM (applyPackageFlag prec_map prelim_pkg_db unusable+                                hide_plugin_pkgs pkgs1)+                             plugin_vis_map1+                             (reverse (unitConfigFlagsPlugins cfg))+                -- Updating based on wired in packages is mostly+                -- good hygiene, because it won't matter: no wired in+                -- package has a compiler plugin.+                -- TODO: If a wired in package had a compiler plugin,+                -- and you tried to pick different wired in packages+                -- with the plugin flags and the normal flags... what+                -- would happen?  I don't know!  But this doesn't seem+                -- likely to actually happen.+                return (updateVisibilityMap wired_map plugin_vis_map2)++  let pkgname_map = listToUFM [ (unitPackageName p, unitInstanceOf p)+                              | p <- pkgs2+                              ]+  -- The explicitUnits accurately reflects the set of units we have turned+  -- on; as such, it also is the only way one can come up with requirements.+  -- The requirement context is directly based off of this: we simply+  -- look for nested unit IDs that are directly fed holes: the requirements+  -- of those units are precisely the ones we need to track+  let explicit_pkgs = [(k, uv_explicit v) | (k, v) <- nonDetUniqMapToList vis_map]+      req_ctx = mapUniqMap (Set.toList)+              $ plusUniqMapListWith Set.union (map uv_requirements (nonDetEltsUniqMap vis_map))+++  --+  -- Here we build up a set of the packages mentioned in -package+  -- flags on the command line; these are called the "preload"+  -- packages.  we link these packages in eagerly.  The preload set+  -- should contain at least rts & base, which is why we pretend that+  -- the command line contains -package rts & -package base.+  --+  -- NB: preload IS important even for type-checking, because we+  -- need the correct include path to be set.+  --+  let preload1 = nonDetKeysUniqMap (filterUniqMap (isJust . uv_explicit) vis_map)++      -- add default preload units if they can be found in the db+      basicLinkedUnits = fmap (RealUnit . Definite)+                         $ filter (flip elemUniqMap pkg_db)+                         $ unitConfigAutoLink cfg+      preload3 = ordNub $ (basicLinkedUnits ++ preload1)++  -- Close the preload packages with their dependencies+  dep_preload <- mayThrowUnitErr+                    $ closeUnitDeps pkg_db+                    $ zip (map toUnitId preload3) (repeat Nothing)++  let mod_map1 = mkModuleNameProvidersMap logger (unitConfigAllowVirtual cfg) pkg_db vis_map+      mod_map2 = mkUnusableModuleNameProvidersMap unusable+      mod_map = mod_map2 `plusUniqMap` mod_map1++  -- Force the result to avoid leaking input parameters+  let !state = UnitState+         { preloadUnits                 = dep_preload+         , explicitUnits                = explicit_pkgs+         , homeUnitDepends              = home_unit_deps+         , unitInfoMap                  = pkg_db+         , trustedUnits                 = trustUnitsOverlay `extendForWireMap` wired_map+         , moduleNameProvidersMap       = mod_map+         , pluginModuleNameProvidersMap = mkModuleNameProvidersMap logger (unitConfigAllowVirtual cfg) pkg_db plugin_vis_map+         , packageNameMap               = pkgname_map+         , requirementContext           = req_ctx+         , allowVirtualUnits            = unitConfigAllowVirtual cfg+         }+  return state++selectHptFlag :: Set.Set UnitId -> PackageFlag -> Bool+selectHptFlag home_units (ExposePackage _ (UnitIdArg uid) _) | toUnitId uid `Set.member` home_units = True+selectHptFlag _ _ = False++selectHomeUnits :: Set.Set UnitId -> [PackageFlag] -> Set.Set UnitId+selectHomeUnits home_units flags = foldl' go Set.empty flags+  where+    go :: Set.Set UnitId -> PackageFlag -> Set.Set UnitId+    go cur (ExposePackage _ (UnitIdArg uid) _) | toUnitId uid `Set.member` home_units = Set.insert (toUnitId uid) cur+    -- MP: This does not yet support thinning/renaming+    go cur _ = cur++initUnitDbConfig :: UnitConfig -> UnitDbConfig+initUnitDbConfig uc = UnitDbConfig+  { unitDbConfigFlagsDB = unitConfigFlagsDB uc+  , unitDbConfigProgramName = unitConfigProgramName uc+  , unitDbConfigDBName = unitConfigDBName uc+  , unitDbConfigPlatformArchOS = unitConfigPlatformArchOS uc+  , unitDbConfigGlobalDB = unitConfigGlobalDB uc+  , unitDbConfigGHCDir = unitConfigGHCDir uc+  }++-- -----------------------------------------------------------------------------+-- Package Utils++-- | Takes a 'ModuleName', and if the module is in any package returns+-- list of modules which take that name.+lookupModuleInAllUnits :: UnitState+                          -> ModuleName+                          -> [(Module, UnitInfo)]+lookupModuleInAllUnits pkgs m+  = case lookupModuleWithSuggestions pkgs m NoPkgQual of+      LookupFound a b -> [(a,fst b)]+      LookupMultiple rs -> map f rs+        where f (m,_) = (m, expectJust (lookupUnit pkgs (moduleUnit m)))+      _ -> []++-- | The result of performing a lookup+data LookupResult =+    -- | Found the module uniquely, nothing else to do+    LookupFound Module (UnitInfo, ModuleOrigin)+    -- | Multiple modules with the same name in scope+  | LookupMultiple [(Module, ModuleOrigin)]+    -- | No modules found, but there were some hidden ones with+    -- an exact name match.  First is due to package hidden, second+    -- is due to module being hidden+  | LookupHidden [UnitInfo] [(Module, ModuleOrigin)]+    -- | No modules found, but there were some unusable ones with+    -- an exact name match+  | LookupUnusable [(Module, ModuleOrigin)]+    -- | Nothing found, here are some suggested different names+  | LookupNotFound [ModuleSuggestion] -- suggestions++data ModuleSuggestion = SuggestVisible ModuleName Module ModuleOrigin+                      | SuggestHidden ModuleName Module ModuleOrigin++lookupModuleWithSuggestions :: UnitState+                            -> ModuleName+                            -> PkgQual+                            -> LookupResult+lookupModuleWithSuggestions pkgs+  = lookupModuleWithSuggestions' pkgs (moduleNameProvidersMap pkgs)++-- | The package which the module **appears** to come from, this could be+-- the one which reexports the module from it's original package. This function+-- is currently only used for -Wunused-packages+lookupModulePackage :: UnitState -> ModuleName -> PkgQual -> Maybe [UnitInfo]+lookupModulePackage pkgs mn mfs =+    case lookupModuleWithSuggestions' pkgs (moduleNameProvidersMap pkgs) mn mfs of+      LookupFound _ (orig_unit, origin) ->+        case origin of+          ModOrigin {fromOrigUnit, fromExposedReexport} ->+            case fromOrigUnit of+              -- Just True means, the import is available from its original location+              Just True ->+                pure [orig_unit]+              -- Otherwise, it must be available from a reexport+              _ -> pure fromExposedReexport++          _ -> Nothing++      _ -> Nothing++lookupPluginModuleWithSuggestions :: UnitState+                                  -> ModuleName+                                  -> PkgQual+                                  -> LookupResult+lookupPluginModuleWithSuggestions pkgs+  = lookupModuleWithSuggestions' pkgs (pluginModuleNameProvidersMap pkgs)++lookupModuleWithSuggestions' :: UnitState+                            -> ModuleNameProvidersMap+                            -> ModuleName+                            -> PkgQual+                            -> LookupResult+lookupModuleWithSuggestions' pkgs mod_map name mb_pn+  = case lookupUniqMap mod_map name of+        Nothing -> LookupNotFound suggestions+        Just xs ->+          case foldl' classify ([],[],[], []) (sortOn fst $ nonDetUniqMapToList xs) of+            ([], [], [], []) -> LookupNotFound suggestions+            (_, _, _, [(m, o)])             -> LookupFound m (mod_unit m, o)+            (_, _, _, exposed@(_:_))        -> LookupMultiple exposed+            ([], [], unusable@(_:_), [])    -> LookupUnusable unusable+            (hidden_pkg, hidden_mod, _, []) ->+              LookupHidden hidden_pkg hidden_mod+  where+    classify (hidden_pkg, hidden_mod, unusable, exposed) (m, origin0) =+      let origin = filterOrigin mb_pn (mod_unit m) origin0+          x = (m, origin)+      in case origin of+          ModHidden+            -> (hidden_pkg, x:hidden_mod, unusable, exposed)+          ModUnusable _+            -> (hidden_pkg, hidden_mod, x:unusable, exposed)+          ModOrigin { fromOrigUnit = origAvailableUnderSameName, fromHiddenReexport }+            | originEmpty origin+            -> (hidden_pkg,   hidden_mod, unusable, exposed)+            | originVisible origin+            -> (hidden_pkg, hidden_mod, unusable, x:exposed)+            | otherwise+            -> (reexports ++ maybe id (:) origUnit hidden_pkg, hidden_mod, unusable, exposed)+            where+              reexports :: [UnitInfo]+              reexports = sortOn unitId fromHiddenReexport++              origUnit :: Maybe UnitInfo+              origUnit = origAvailableUnderSameName >> lookupUnit pkgs (moduleUnit m)++    unit_lookup p = lookupUnit pkgs p `orElse` pprPanic "lookupModuleWithSuggestions" (ppr p <+> ppr name)+    mod_unit = unit_lookup . moduleUnit++    -- Filters out origins which are not associated with the given package+    -- qualifier.  No-op if there is no package qualifier.  Test if this+    -- excluded all origins with 'originEmpty'.+    filterOrigin :: PkgQual+                 -> UnitInfo+                 -> ModuleOrigin+                 -> ModuleOrigin+    filterOrigin NoPkgQual _ o = o+    filterOrigin (ThisPkg _) _ o = o+    filterOrigin (OtherPkg u) pkg o =+      let match_pkg p = u == unitId p+      in case o of+          ModHidden+            | match_pkg pkg -> ModHidden+            | otherwise     -> mempty+          ModUnusable _+            | match_pkg pkg -> o+            | otherwise     -> mempty+          ModOrigin { fromOrigUnit = e, fromExposedReexport = res,+                      fromHiddenReexport = rhs }+            -> ModOrigin+                { fromOrigUnit        = if match_pkg pkg then e else Nothing+                , fromExposedReexport = filter match_pkg res+                , fromHiddenReexport  = filter match_pkg rhs+                , fromPackageFlag     = False -- always excluded+                }++    suggestions = fuzzyLookup (moduleNameString name) all_mods++    all_mods :: [(String, ModuleSuggestion)]     -- All modules+    all_mods = sortOn fst $+        [ (moduleNameString m, suggestion)+        | (m, e) <- nonDetUniqMapToList (moduleNameProvidersMap pkgs)+        , suggestion <- map (getSuggestion m) (nonDetUniqMapToList e)+        ]+    getSuggestion name (mod, origin) =+        (if originVisible origin then SuggestVisible else SuggestHidden)+            name mod origin++listVisibleModuleNames :: UnitState -> [ModuleName]+listVisibleModuleNames state =+    map fst (filter visible (nonDetUniqMapToList (moduleNameProvidersMap state)))+  where visible (_, ms) = anyUniqMap originVisible ms++++-- | Return this list of requirement interfaces that need to be merged+-- to form @mod_name@, or @[]@ if this is not a requirement.+requirementMerges :: UnitState -> ModuleName -> [InstantiatedModule]+requirementMerges pkgstate mod_name =+  fromMaybe [] (lookupUniqMap (requirementContext pkgstate) mod_name)++-- -----------------------------------------------------------------------------++-- | Pretty-print a UnitId for the user.+--+-- Cabal packages may contain several components (programs, libraries, etc.).+-- As far as GHC is concerned, installed package components ("units") are+-- identified by an opaque UnitId string provided by Cabal. As the string+-- contains a hash, we don't want to display it to users so GHC queries the+-- database to retrieve some infos about the original source package (name,+-- version, component name).+--+-- Instead we want to display: packagename-version[:componentname]+--+-- Component name is only displayed if it isn't the default library+--+-- To do this we need to query a unit database.+pprUnitIdForUser :: UnitState -> UnitId -> SDoc+pprUnitIdForUser state uid@(UnitId fs) =+   case lookupUnitPprInfo state uid of+      Nothing -> ftext fs -- we didn't find the unit at all+      Just i  -> ppr i++pprUnitInfoForUser :: UnitInfo -> SDoc+pprUnitInfoForUser info = ppr (mkUnitPprInfo unitIdFS info)++lookupUnitPprInfo :: UnitState -> UnitId -> Maybe UnitPprInfo+lookupUnitPprInfo state uid = fmap (mkUnitPprInfo unitIdFS) (lookupUnitId state uid)++-- -----------------------------------------------------------------------------+-- Displaying packages++-- | Show (very verbose) package info+pprUnits :: UnitState -> SDoc+pprUnits = pprUnitsWith pprUnitInfo++pprUnitsWith :: (UnitInfo -> SDoc) -> UnitState -> SDoc+pprUnitsWith pprIPI pkgstate =+    vcat (intersperse (text "---") (map pprIPI (listUnitInfo pkgstate)))++-- | Show simplified unit info.+--+-- The idea is to only print package id, and any information that might+-- be different from the package databases (exposure, trust)+pprUnitsSimple :: UnitState -> SDoc+pprUnitsSimple ue = pprUnitsWith pprIPI ue+    where pprIPI ipi = let i = unitIdFS (unitId ipi)+                           e = if unitIsExposed ipi then text "E" else text " "+                           t = if isUnitInfoTrusted ue ipi then text "T" else text " "+                       in e <> t <> text "  " <> ftext i++-- | Print unit-ids with UnitInfo found in the given UnitState+pprWithUnitState :: UnitState -> SDoc -> SDoc+pprWithUnitState state = updSDocContext (\ctx -> ctx+   { sdocUnitIdForUser = \fs -> pprUnitIdForUser state (UnitId fs)+   })++-- | Print raw unit-ids, without removing the hash+pprRawUnitIds :: SDoc -> SDoc+pprRawUnitIds = updSDocContext (\ctx -> ctx { sdocUnitIdForUser = ftext })++fsPackageName :: UnitInfo -> FastString+fsPackageName info = fs+   where+      PackageName fs = unitPackageName info++-- -----------------------------------------------------------------------------+-- Module renaming++-- | Substitutes holes in a 'Module'.  NOT suitable for being called+-- directly on a 'nameModule', see Note [Representation of module/name variables].+-- @p[A=\<A>]:B@ maps to @p[A=q():A]:B@ with @A=q():A@;+-- similarly, @\<A>@ maps to @q():A@.+renameHoleModule :: UnitState -> ShHoleSubst -> Module -> Module+renameHoleModule state = renameHoleModule' (unitInfoMap state)++-- | Substitutes holes in a 'Unit', suitable for renaming when+-- an include occurs; see Note [Representation of module/name variables].+--+-- @p[A=\<A>]@ maps to @p[A=\<B>]@ with @A=\<B>@.+renameHoleUnit :: UnitState -> ShHoleSubst -> Unit -> Unit+renameHoleUnit state = renameHoleUnit' (unitInfoMap state)++-- | Injects an 'InstantiatedModule' to 'Module' (see also+-- 'instUnitToUnit'.+instModuleToModule :: InstantiatedModule -> Module+instModuleToModule (Module iuid mod_name) =+    mkModule (instUnitToUnit iuid) mod_name++-- | Return a `UnitId` which either wraps the `InstantiatedUnit` unchanged.+instUnitToUnit :: InstantiatedUnit -> Unit+instUnitToUnit iuid =+    -- NB: suppose that we want to compare the instantiated+    -- unit p[H=impl:H] against p+abcd (where p+abcd+    -- happens to be the existing, installed version of+    -- p[H=impl:H].  If we *only* wrap in p[H=impl:H]+    -- VirtUnit, they won't compare equal; only+    -- after improvement will the equality hold.+    VirtUnit iuid
GHC/Unit/Types.hs view
@@ -257,9 +257,7 @@ -- -- This unit may be indefinite or not (i.e. with remaining holes or not). If it -- is definite, we don't know if it has already been compiled and installed in a--- database. Nevertheless, we have a mechanism called "improvement" to try to--- match a fully instantiated unit with existing compiled and installed units:--- see Note [VirtUnit to RealUnit improvement].+-- database. -- -- An indefinite unit identifier pretty-prints to something like -- @p[H=<H>,A=aimpl:A>]@ (@p@ is the 'UnitId', and the@@ -587,7 +585,7 @@ The affected packages are compiled with, e.g., @-this-unit-id base@, so that the symbols in the object files have the unversioned unit id in their name. -Make sure you change 'GHC.Unit.State.findWiredInUnits' if you add an entry here.+Make sure you change 'wiredInUnitIds' if you add an entry here.  -} @@ -664,7 +662,7 @@  Note that we also ensure the ghc's unit key matches its unit id, both when hadrian or cabal is building ghc. This way, we no longer need to add `ghc` to-the WiringMap, and that's why 'wiredInUnitIds' no longer includes+the WireMap, and that's why 'wiredInUnitIds' no longer includes 'thisGhcUnitId'. -} 
GHC/Utils/Binary.hs view
@@ -1869,172 +1869,6 @@   put_ bh (ModuleName fs) = put_ bh fs   get bh = do fs <- get bh; return (ModuleName fs) --- instance Binary TupleSort where---     put_ bh BoxedTuple      = putByte bh 0---     put_ bh UnboxedTuple    = putByte bh 1---     put_ bh ConstraintTuple = putByte bh 2---     get bh = do---       h <- getByte bh---       case h of---         0 -> do return BoxedTuple---         1 -> do return UnboxedTuple---         _ -> do return ConstraintTuple---- instance Binary Activation where---     put_ bh NeverActive = do---             putByte bh 0---     put_ bh FinalActive = do---             putByte bh 1---     put_ bh AlwaysActive = do---             putByte bh 2---     put_ bh (ActiveBefore src aa) = do---             putByte bh 3---             put_ bh src---             put_ bh aa---     put_ bh (ActiveAfter src ab) = do---             putByte bh 4---             put_ bh src---             put_ bh ab---     get bh = do---             h <- getByte bh---             case h of---               0 -> do return NeverActive---               1 -> do return FinalActive---               2 -> do return AlwaysActive---               3 -> do src <- get bh---                       aa <- get bh---                       return (ActiveBefore src aa)---               _ -> do src <- get bh---                       ab <- get bh---                       return (ActiveAfter src ab)---- instance Binary InlinePragma where---     put_ bh (InlinePragma s a b c d) = do---             put_ bh s---             put_ bh a---             put_ bh b---             put_ bh c---             put_ bh d----     get bh = do---            s <- get bh---            a <- get bh---            b <- get bh---            c <- get bh---            d <- get bh---            return (InlinePragma s a b c d)---- instance Binary RuleMatchInfo where---     put_ bh FunLike = putByte bh 0---     put_ bh ConLike = putByte bh 1---     get bh = do---             h <- getByte bh---             if h == 1 then return ConLike---                       else return FunLike---- instance Binary InlineSpec where---     put_ bh NoUserInlinePrag = putByte bh 0---     put_ bh Inline           = putByte bh 1---     put_ bh Inlinable        = putByte bh 2---     put_ bh NoInline         = putByte bh 3----     get bh = do h <- getByte bh---                 case h of---                   0 -> return NoUserInlinePrag---                   1 -> return Inline---                   2 -> return Inlinable---                   _ -> return NoInline---- instance Binary RecFlag where---     put_ bh Recursive = do---             putByte bh 0---     put_ bh NonRecursive = do---             putByte bh 1---     get bh = do---             h <- getByte bh---             case h of---               0 -> do return Recursive---               _ -> do return NonRecursive---- instance Binary OverlapMode where---     put_ bh (NoOverlap    s) = putByte bh 0 >> put_ bh s---     put_ bh (Overlaps     s) = putByte bh 1 >> put_ bh s---     put_ bh (Incoherent   s) = putByte bh 2 >> put_ bh s---     put_ bh (Overlapping  s) = putByte bh 3 >> put_ bh s---     put_ bh (Overlappable s) = putByte bh 4 >> put_ bh s---     get bh = do---         h <- getByte bh---         case h of---             0 -> (get bh) >>= \s -> return $ NoOverlap s---             1 -> (get bh) >>= \s -> return $ Overlaps s---             2 -> (get bh) >>= \s -> return $ Incoherent s---             3 -> (get bh) >>= \s -> return $ Overlapping s---             4 -> (get bh) >>= \s -> return $ Overlappable s---             _ -> panic ("get OverlapMode" ++ show h)----- instance Binary OverlapFlag where---     put_ bh flag = do put_ bh (overlapMode flag)---                       put_ bh (isSafeOverlap flag)---     get bh = do---         h <- get bh---         b <- get bh---         return OverlapFlag { overlapMode = h, isSafeOverlap = b }---- instance Binary FixityDirection where---     put_ bh InfixL = do---             putByte bh 0---     put_ bh InfixR = do---             putByte bh 1---     put_ bh InfixN = do---             putByte bh 2---     get bh = do---             h <- getByte bh---             case h of---               0 -> do return InfixL---               1 -> do return InfixR---               _ -> do return InfixN---- instance Binary Fixity where---     put_ bh (Fixity src aa ab) = do---             put_ bh src---             put_ bh aa---             put_ bh ab---     get bh = do---           src <- get bh---           aa <- get bh---           ab <- get bh---           return (Fixity src aa ab)---- instance Binary WarningTxt where---     put_ bh (WarningTxt s w) = do---             putByte bh 0---             put_ bh s---             put_ bh w---     put_ bh (DeprecatedTxt s d) = do---             putByte bh 1---             put_ bh s---             put_ bh d----     get bh = do---             h <- getByte bh---             case h of---               0 -> do s <- get bh---                       w <- get bh---                       return (WarningTxt s w)---               _ -> do s <- get bh---                       d <- get bh---                       return (DeprecatedTxt s d)---- instance Binary StringLiteral where---   put_ bh (StringLiteral st fs _) = do---             put_ bh st---             put_ bh fs---   get bh = do---             st <- get bh---             fs <- get bh---             return (StringLiteral st fs Nothing)- newtype BinLocated a = BinLocated { unBinLocated :: Located a }  instance Binary a => Binary (BinLocated a) where@@ -2085,6 +1919,7 @@       _ -> UnhelpfulOther <$> get bh  newtype BinSrcSpan = BinSrcSpan { unBinSrcSpan :: SrcSpan }+  deriving newtype NFData  -- See Note [Source Location Wrappers] instance Binary BinSrcSpan where
GHC/Utils/Logger.hs view
@@ -62,6 +62,8 @@     , logJsonMsg     , logDumpMsg +    , decorateDiagnostic+     -- * Dumping     , defaultDumpAction     , putDumpFile@@ -419,26 +421,62 @@       MCInfo                       -> printErrs msg       MCFatal                      -> printErrs msg       MCDiagnostic SevIgnore _ _   -> pure () -- suppress the message-      MCDiagnostic _sev _rea _code -> printDiagnostics+      MCDiagnostic _sev _rea _code -> decorateDiagnostic logflags msg_class srcSpan msg >>= printErrs     where       printOut   = defaultLogActionHPrintDoc  logflags False out       printErrs  = defaultLogActionHPrintDoc  logflags False err       putStrSDoc = defaultLogActionHPutStrDoc logflags False out++-- This function is used by `defaultLogActionWithHandles` for non-JSON output,+-- and also by `GHC.Driver.Errors.printMessages` to produce the `rendered`+-- message on `-fdiagnostics-as-json`.+--+-- We would want to eventually consolidate this.  However, this is currently+-- not feasible for the following reasons:+--+-- 1. Some parts of the compiler sidestep `printMessages`, for that reason we+--    can not decorate the message in `printMessages`.+--+-- 2. GHC uses two different code paths for JSON and non-JSON diagnostics.  For+--    that reason we can not decorate the message in `defaultLogActionWithHandles`.+--+--    See also Note [JSON Error Messages]:+--+--      `jsonLogAction` should be removed along with -ddump-json+--+-- Also note that (1) is the reason why some parts of the compiler produce+-- diagnostics that don't respect `-fdiagnostics-as-json`.+--+-- The plan as I see it is as follows:+--+--  1. Refactor all places in the compiler that report diagnostics to go+--     through `GHC.Driver.Errors.printMessages`.+--+--     (It's easy to find all those places by looking for who creates+--     MCDiagnostic, either directly or via `mkMCDiagnostic` or+--     `errorDiagnostic`.)+--+--  2. Get rid of `-ddump-json`, `jsonLogAction` and consolidate message+--     decoration at one place (either `printMessages` or+--     `defaultLogActionWithHandles`)+--+-- This story is tracked by #24113.+decorateDiagnostic :: LogFlags -> MessageClass -> SrcSpan -> SDoc -> IO SDoc+decorateDiagnostic logflags msg_class srcSpan msg = addCaret+    where       -- Pretty print the warning flag, if any (#10752)+      message :: SDoc       message = mkLocMessageWarningGroups (log_show_warn_groups logflags) msg_class srcSpan msg -      printDiagnostics = do+      addCaret :: IO SDoc+      addCaret = do         caretDiagnostic <-             if log_show_caret logflags             then getCaretDiagnostic msg_class srcSpan             else pure empty-        printErrs $ getPprStyle $ \style ->+        return $ getPprStyle $ \style ->           withPprStyle (setStyleColoured True style)             (message $+$ caretDiagnostic $+$ blankLine)-        -- careful (#2302): printErrs prints in UTF-8,-        -- whereas converting to string first and using-        -- hPutStr would just emit the low 8 bits of-        -- each unicode char.  -- | Like 'defaultLogActionHPutStrDoc' but appends an extra newline. defaultLogActionHPrintDoc :: LogFlags -> Bool -> Handle -> SDoc -> IO ()@@ -603,8 +641,8 @@ logMsg :: Logger -> MessageClass -> SrcSpan -> SDoc -> IO () logMsg logger mc loc msg = putLogMsg logger (logFlags logger) mc loc msg -logJsonMsg :: ToJson a => Logger -> MessageClass -> a -> IO ()-logJsonMsg logger mc d = putJsonLogMsg logger (logFlags logger) mc  (json d)+logJsonMsg :: Logger -> MessageClass -> JsonDoc -> IO ()+logJsonMsg logger mc = putJsonLogMsg logger (logFlags logger) mc  -- | Dump something logDumpFile :: Logger -> PprStyle -> DumpFlag -> String -> DumpFormat -> SDoc -> IO ()
GHC/Utils/Misc.hs view
@@ -137,6 +137,8 @@ import Control.Monad.IO.Class ( MonadIO, liftIO ) import System.IO.Error as IO ( isDoesNotExistError ) import System.Directory ( doesDirectoryExist, getModificationTime, renameFile )+import qualified System.Directory.OsPath as OsPath+import System.OsPath (OsPath) import System.FilePath  import Data.Bifunctor   ( first, second )@@ -1248,9 +1250,9 @@ -- -------------------------------------------------------------- -- check existence & modification time at the same time -modificationTimeIfExists :: FilePath -> IO (Maybe UTCTime)+modificationTimeIfExists :: OsPath -> IO (Maybe UTCTime) modificationTimeIfExists f =-  (do t <- getModificationUTCTime f; return (Just t))+  (do t <- OsPath.getModificationTime f; return (Just t))         `catchIO` \e -> if isDoesNotExistError e                         then return Nothing                         else ioError e
GHC/Utils/Outputable.hs view
@@ -148,6 +148,7 @@ import Data.Word import System.IO        ( Handle ) import System.FilePath+import System.OsPath (OsPath, decodeUtf) import Text.Printf import Numeric (showFFloat) import Data.Graph (SCC(..))@@ -1080,6 +1081,8 @@ instance Outputable ModuleName where   ppr = pprModuleName +instance Outputable OsPath where+  ppr p = text $ either show id (decodeUtf p)  pprModuleName :: IsLine doc => ModuleName -> doc pprModuleName (ModuleName nm) =
Language/Haskell/Syntax/Module/Name.hs view
@@ -17,7 +17,8 @@   -- don't traverse?   toConstr x   = constr     where-      constr = mkConstr (dataTypeOf x) "{abstract:ModuleName}" [] Prefix+      -- Fake a Algebraic constr. See #27129+      constr = mkConstrTag (dataTypeOf x) "{abstract:ModuleName}" 1 [] Prefix   gunfold _ _  = error "gunfold"   dataTypeOf _ = mkNoRepType "ModuleName" 
ghc.cabal view
@@ -3,7 +3,7 @@ -- ./configure.  Make sure you are editing ghc.cabal.in, not ghc.cabal.  Name: ghc-Version: 9.14.1+Version: 9.14.2 License: BSD-3-Clause License-File: LICENSE Author: The GHC Team@@ -131,17 +131,17 @@                    semaphore-compat,                    stm,                    rts,-                   ghc-boot   == 9.14.1,-                   ghc-heap   >=9.10.1 && <=9.14.1,-                   ghci == 9.14.1+                   ghc-boot   == 9.14.2,+                   ghc-heap   >=9.10.1 && <=9.14.2,+                   ghci == 9.14.2      if flag(bootstrap)       Build-Depends:-        ghc-boot-th-next     == 9.14.1+        ghc-boot-th-next     == 9.14.2     else       Build-Depends:-        ghc-boot-th          == 9.14.1,-        ghc-internal         == 9.1401.0,+        ghc-boot-th          == 9.14.2,+        ghc-internal         == 9.1402.0,      if os(windows)         Build-Depends: Win32  >= 2.3 && < 2.15@@ -325,6 +325,7 @@         GHC.CmmToAsm.Reg.Linear.X86         GHC.CmmToAsm.Reg.Linear.X86_64         GHC.CmmToAsm.Reg.Liveness+        GHC.CmmToAsm.Reg.Regs         GHC.CmmToAsm.Reg.Target         GHC.CmmToAsm.Reg.Utils         GHC.CmmToAsm.RV64@@ -573,6 +574,7 @@         GHC.HsToCore.Arrows         GHC.HsToCore.Binds         GHC.HsToCore.Breakpoints+        GHC.HsToCore.Breakpoints.Types         GHC.HsToCore.Coverage         GHC.HsToCore.Docs         GHC.HsToCore.Errors.Ppr@@ -956,6 +958,15 @@         GHC.Unit         GHC.Unit.Env         GHC.Unit.External+        GHC.Unit.External.Database+        GHC.Unit.External.Index+        GHC.Unit.External.ModuleOrigin+        GHC.Unit.External.Providers+        GHC.Unit.External.Query+        GHC.Unit.External.Substitution+        GHC.Unit.External.Validate+        GHC.Unit.External.Visibility+        GHC.Unit.External.Wired         GHC.Unit.Finder         GHC.Unit.Finder.Types         GHC.Unit.Home