-- | Ownership (L4a, language 6.3, SPARK RM 3.10): a value of a pool-specific access type -- owns what it designates, so assigning it moves it. Flow analysis follows, on every path, -- which parts of which objects have been moved out, and rejects reading a moved part (or a -- whole that contains one), writing into what a moved access value designated, moving out of -- an `in` parameter (which the caller still owns), and returning while an `in out` or `out` -- parameter or a global still has a moved part. A move is undone by assigning the whole moved -- part again. -- -- The move states at each point where objects die are what L4b's finalization will need -- (language 6.3, the design constraint): they are computed here once and exposed through -- 'deathStates'. module Verada.Flow.Ownership ( DeathPoint (..) , Place (..) , Step (..) , checkOwnership ) where import Verada.BIR.Expr import Verada.BIR.Moves (deallocationName, isOwning) import Verada.BIR.Stmt import Verada.BIR.Traverse (statementExpressions, universeExpressions, universeStatements) import Verada.BIR.Types import Verada.Diagnostics (Diagnostic (..), Label (..), Phase (..), diagnostic, label) import Verada.Diagnostics.Codes (DiagCode (..)) import Verada.Source (Span) import Verada.TAST.Decl (ParamMode (..)) import Control.Applicative ((<|>)) import Control.Monad (forM_, when) import Control.Monad.State.Strict (State, execState, gets, modify') import Data.IntMap.Strict qualified as IntMap import Data.List (find, isPrefixOf) import Data.Map.Strict (Map) import Data.Map.Strict qualified as Map import Data.Maybe (catMaybes, fromMaybe) import Data.Set (Set) import Data.Set qualified as Set import Data.Text qualified as Text -- | A part of an object: a variable and the components, indices and designated objects on -- the way to the part (any index stands for every index). data Place = Place { root :: VarId , steps :: [Step] } deriving stock (Eq, Ord, Show) data Step = SField Int | SIndex | SDeref deriving stock (Eq, Ord, Show) -- | The parts moved out on a path, each with where it was moved. type Moved = Map Place Span -- | Where objects die (a scope exit or a return) and which of their parts are moved there. data DeathPoint = DeathPoint { span :: Maybe Span , dying :: [VarId] , moved :: [Place] } deriving stock (Eq, Show) data OwnState = OwnState { exits :: Map LoopId [Moved] , diagnostics :: [Diagnostic] , reported :: Set (Maybe Span, DiagCode) , deaths :: [DeathPoint] , reporting :: Bool -- ^ off while a loop's states are still being found (its body is analysed again) , observers :: Map VarId (VarId, Maybe Span) , raisedStates :: [Moved] -- ^ the states where exceptions were raised that no handler has taken yet , pinned :: Map VarId (Maybe Span) -- ^ the objects a general access value took with `X'Access` (G6), each with where: used -- only through that value from then on , borrowers :: Map VarId (VarId, Maybe Span) -- ^ the live borrowers (objects of anonymous access-to-variable types), each with the owner -- it borrowed from and where; the owner is unusable while one lives -- ^ the live observers (objects of anonymous access-to-constant types), each with the owner -- whose structure it observes and where it began to } type Analysis = State OwnState isPrefixPlace :: Place -> Place -> Bool isPrefixPlace a b = a.root == b.root && a.steps `isPrefixOf` b.steps -- | The place an expression names, when it is a name (a variable or a part of one). placeOf :: BExpr -> Maybe Place placeOf e = case e.node of BVar v -> Just Place {root = v, steps = []} BField f -> extend (SField f.field) <$> placeOf f.record BIndex ix -> extend SIndex <$> placeOf ix.array BDeref x -> extend SDeref <$> placeOf x BSlice s -> placeOf s.array -- `X'Access` names the part it designates BBorrow b -> Just Place {root = b.root, steps = concatMap stepOf b.path} BConvert x | sameShape x.typ e.typ -> placeOf x _ -> Nothing where extend s p = Place {root = p.root, steps = p.steps <> [s]} -- (a view of a class-wide object as one of its types is the same object) stepOf = \case StepField k -> [SField k] StepIndex _ -> [SIndex] StepDeref -> [SDeref] StepAs _ -> [] -- a conversion between array forms names the same object sameShape a b = case (a, b) of (ArrayOf _, ArrayValue _) -> True (ArrayValue _, ArrayOf _) -> True _ -> False -- | Whether a type is a named general access type (`access all`), whose values take the -- objects they designate for good (G6). generalAccess :: BType -> Bool generalAccess = \case AccessOf a -> a.general _ -> False placeOfPath :: VarId -> [PathStep] -> Place placeOfPath v path = Place {root = v, steps = concatMap one path} where one = \case StepIndex _ -> [SIndex] StepField k -> [SField k] StepDeref -> [SDeref] StepAs _ -> [] -- | The ownership diagnostics of each subprogram of a program (applied to the program once, -- then to each subprogram: what the whole program pins is found once). checkOwnership :: BProgram -> BSubprogram -> [Diagnostic] checkOwnership p = \sub -> reverse (analyse p pins sub).diagnostics where pins = globalPins p -- | The library-level objects a general access value takes, wherever it takes them (their -- elaboration, usually). globalPins :: BProgram -> Map VarId (Maybe Span) globalPins p = Map.fromList [(b.root, e.span) | s <- p.subprograms, Just body <- [s.body], e <- concatMap universeExpressions (concatMap statementExpressions (universeStatements body)), BBorrow b <- [e.node], generalAccess e.typ, any (\g -> g.var.varId == b.root) p.globals] analyse :: BProgram -> Map VarId (Maybe Span) -> BSubprogram -> OwnState analyse p programPins sub = case sub.body of Nothing -> start Just body -> execState (run body) start where start = OwnState {exits = Map.empty, diagnostics = [], reported = Set.empty, deaths = [], reporting = True, observers = Map.empty, borrowers = Map.empty, raisedStates = [], pinned = programPins} vars = sub.variables varOf v = case IntMap.lookup (key v) vars of Just x -> Just x Nothing -> (.var) <$> find (\g -> g.var.varId == v) p.globals nameOf v = maybe "?" (.name) (varOf v) roleOf v = maybe Temporary (.role) (varOf v) typeOfVar v = maybe (Scalar BooleanScalar) (.typ) (varOf v) isObserver v = case typeOfVar v of AccessOf a -> a.toConstant && roleOf v == Local && a.name `notElem` p.enclaveAccess _ -> False -- what an observer or a borrower is given comes from this part (a traversal function's -- result, from its first actual) ownerOf e = case e.node of BCall c | a : _ <- c.arguments -> ownerOf a _ -> placeOf e isBorrower v = case typeOfVar v of AccessOf a -> a.borrower _ -> False -- the objects that must be whole when the subprogram returns: `in out` and `out` -- parameters, and the globals returned = [v | v <- sub.parameters, roleOf v `elem` [Parameter ModeInOut, Parameter ModeOut], v `notElem` sub.borrowed] run body = do end <- stmts Map.empty body forM_ end (returning (Just sub.span)) stmts :: Moved -> [BStmt] -> Analysis (Maybe Moved) stmts m = \case [] -> pure (Just m) s : rest -> stmt m s >>= \case Nothing -> pure Nothing Just m' -> stmts m' rest stmt :: Moved -> BStmt -> Analysis (Maybe Moved) -- a borrower given back to its owner where its scope ends: the owner is usable again givenBack target value = case value.node of BDeref BExpr {node = BVar b} -> givenBack target BExpr {typ = value.typ, span = value.span, node = BVar b} BVar b -> do known <- gets (Map.lookup b . (.borrowers)) when (fmap fst known == Just target) $ modify' \st -> st {borrowers = Map.delete b st.borrowers} _ -> pure () stmt m s = case s.node of BAssign a -> do givenBack a.target a.value -- an actual lent to a call through a temporary comes back after it; an observer or a -- borrower takes nothing from what it is given m' <- if isOwning (typeOfVar a.target) then (if roleOf a.target == Temporary then moveOrReadLent else moveOrRead) m a.value else do -- what it is given is read first readDeep m a.value -- a borrower: likewise, and the owner is set aside until the borrower ends forM_ (ownerOf a.value) \pl -> when (isBorrower a.target) do known <- gets (Map.lookup pl.root . (.borrowers)) let owner = maybe pl.root fst known when (owner /= a.target) $ modify' \st -> st {borrowers = Map.insert a.target (owner, (snd =<< known) <|> s.span) st.borrowers} -- an observer of a structure: its owner is the owner of what it is given forM_ (ownerOf a.value) \pl -> when (isObserver a.target) do known <- gets (Map.lookup pl.root . (.observers)) let owner = maybe pl.root fst known when (owner /= a.target) $ modify' \st -> st {observers = Map.insert a.target (owner, (snd =<< known) <|> s.span) st.observers} pure m Just <$> assignTo s.span m' Place {root = a.target, steps = []} BAssignPart a -> do givenBack a.target a.value mapM_ (readDeep m) [i | StepIndex i <- a.path] m' <- moveOrRead m a.value Just <$> assignTo s.span m' (placeOfPath a.target a.path) BCallStmt c@CallStmt {callee = Direct d} -> do let modes = calleeModes d -- freeing an object frees nothing it moved out (its moved parts are empty) freeing = any (\x -> x.decl == d && x.imported && x.linkName == deallocationName) p.subprograms -- what a call may change forM_ [v | ByReference v <- c.arguments] \v -> forM_ s.span \at -> changing (Just at) v forM_ (zip [0 :: Int ..] c.arguments) \(k, arg) -> case arg of ByValue e -> readDeep m e ByReference v -- an `out` actual need not be whole: it is assigned by the call | lookupMode k modes == Just ModeOut -> pure () | otherwise -> readPlace (not freeing) m Place {root = v, steps = []} s.span -- (an access value made for the call alone, `X'Access` as an access actual: its -- borrow ends with the call, SPARK RM 3.10, SPARK-05) let forTheCall = [v | ByReference v <- c.arguments, Just x <- [varOf v], x.role == Temporary, "_actual" `Text.isSuffixOf` x.name, AccessOf _ <- [x.typ]] modify' \st -> st {borrowers = Map.filterWithKey (\b _ -> b `notElem` forTheCall) st.borrowers} -- what comes back is whole again pure (Just (foldl (\acc v -> Map.filterWithKey (\k _ -> k.root /= v) acc) m [v | ByReference v <- c.arguments])) BCheck c -> Just m <$ readDeep m c.condition -- (a fact the prover is given reads nothing of the program: a prophecy's of an owner -- whose part is lent, say) BAssertion a | a.kind == Given -> pure (Just m) BAssertion a -> do readDeep m a.condition -- (a message's statements are run only when the assertion fails, which ends the run) forM_ a.message \msg -> stmts m msg.prelude >>= mapM_ (`readDeep` msg.text) pure (Just m) BIf i -> do readDeep m i.condition t <- stmts m i.whenTrue f <- stmts m i.whenFalse pure (joinStates (catMaybesList [t, f])) BLoop l -> loop s.span m l BExit l -> do modify' \st -> st {exits = Map.insertWith (<>) l [m] st.exits} pure Nothing -- (a traversal function's result borrows or observes a part of its first parameter, -- which its caller keeps: nothing moves, SPARK RM 3.10(7)) BReturn v | Just (AccessOf a) <- sub.result, a.borrower -> do mapM_ (readDeep m) v returning s.span m pure Nothing BReturn v -> do m' <- maybe (pure m) (moveOrRead m) v returning s.span m' pure Nothing BCallStmt c@CallStmt {callee = Indirect callTarget} -> do readDeep m callTarget forM_ c.arguments \case ByValue e -> readDeep m e ByReference v -> readPlace True m Place {root = v, steps = []} s.span pure (Just (foldl (\acc v -> Map.filterWithKey (\k _ -> k.root /= v) acc) m [v | ByReference v <- c.arguments])) BRaise r -> do mapM_ (readDeep m) r.message modify' \st -> st {raisedStates = m : st.raisedStates} pure Nothing BHavoc _ -> pure (Just m) -- a handler starts from any state an exception was raised in (or, conservatively, -- from the start); those raised states also go on to the handlers further out BHandle h -> do outer <- gets (.raisedStates) modify' \st -> st {raisedStates = []} afterBody <- stmts m h.body inner <- gets (.raisedStates) modify' \st -> st {raisedStates = inner <> outer} let entry = fromMaybe m (joinStates (m : inner)) ends <- mapM (stmts entry . (.body)) h.handlers pure (joinStates (catMaybesList (afterBody : ends))) BScopeExit dying -> do death s.span dying m modify' \st -> st {observers = Map.filterWithKey (\o _ -> o `notElem` dying) st.observers} modify' \st -> st {borrowers = Map.filterWithKey (\o _ -> o `notElem` dying) st.borrowers} pure (Just (Map.filterWithKey (\k _ -> k.root `notElem` dying) m)) BVariant v -> Just m <$ mapM_ (readDeep m . snd) v.parts -- a loop: its head's state is the entry's joined with every iteration's end, found by -- analysing the body until it no longer grows (quietly), then once more reporting loop at m l = do saved <- gets (.exits) quiet <- gets (.reporting) modify' \st -> st {reporting = False} headState <- fixpoint (8 :: Int) m modify' \st -> st {reporting = quiet, exits = saved} end <- stmts headState l.body -- an iteration ends with nothing moved that was not moved when the loop began, so -- every iteration starts alike (SPARK RM 3.10(14)) forM_ end \e -> forM_ (Map.toList e) \(mv, movedAt) -> when (Map.notMember mv m) do report MovedInLoop (Just movedAt) (Just movedAt) ("`" <> describe mv <> "` is still moved at the end of an iteration of the loop") (Just "moved here") [Label {span = sp, text = Just "the loop"} | Just sp <- [at]] (Just "give it a new value before the iteration ends, or declare it inside the loop") leaving <- gets (Map.findWithDefault [] l.loop . (.exits)) modify' \st -> st {exits = Map.delete l.loop st.exits} _ <- pure end pure (joinStates leaving) where fixpoint n h = do end <- stmts h l.body modify' \st -> st {exits = Map.delete l.loop st.exits} let h' = maybe h (Map.union h) end if Map.keysSet h' == Map.keysSet h || n <= 0 then pure h' else fixpoint (n - 1) h' joinStates = \case [] -> Nothing ms -> Just (Map.unions ms) catMaybesList = catMaybes -- an assigned value: moved when it names an owning part, otherwise read; a general access -- value's `X'Access` takes X for good (G6) moveOrRead m e = case (e.node, placeOf e) of (BBorrow b, Just pl) | generalAccess e.typ -> do readPlace True m pl e.span observed pl e.span modify' \st -> st {pinned = Map.insert b.root e.span st.pinned} pure m _ -> moveOrRead' m e moveOrRead' m e = case placeOf e of Just pl | isOwning e.typ -> do changing e.span pl.root readPlace True m pl e.span observed pl e.span pure (maybe m (\at -> Map.insert pl at m) e.span) _ -> m <$ readDeep m e moveOrReadLent m e = case placeOf e of Just pl | isOwning e.typ -> do readPlace True m pl e.span pure (maybe m (\at -> Map.insert pl at m) e.span) _ -> m <$ readDeep m e -- moving out of an `in` parameter would take what the caller still owns observed pl at = if roleOf pl.root /= Parameter ModeIn && pl.root `notElem` sub.borrowed then pure () else report MoveFromObserved at at ("`" <> nameOf pl.root <> "` is an `in` parameter, so its value cannot be moved") (Just "the caller still owns it") [] (Just "copy what you need, or make the parameter `in out` and give it a new value") -- writing a part: everything in it is whole again; writing into a moved part is an error assignTo at m target = do changing at target.root forM_ (Map.toList m) \(mv, movedAt) -> when (isPrefixPlace mv target && mv /= target && SDeref `elem` drop (length mv.steps) target.steps) do report UseAfterMove (Just movedAt) at ("`" <> describe mv <> "` was moved, so what it designated can no longer be written through it") (Just "written here") [Label {span = movedAt, text = Just "moved here"}] (Just "assign it a new value first") pure (Map.filterWithKey (\k _ -> not (isPrefixPlace target k)) m) -- a borrowed owner is unusable while a borrower of it lives (SPARK RM 3.10); one a general -- access value took, from then on unusable at root = do pins <- gets (.pinned) forM_ (Map.lookup root pins) \from -> when (from /= at) do report UseAfterMove from at ("`" <> nameOf root <> "` is designated by a general access value since its `'Access`, so it is used only through that value") (Just "used here") [Label {span = sp, text = Just "taken here"} | Just sp <- [from]] (Just ("read and write it through the access value made from `" <> nameOf root <> "'Access`")) lending <- gets (Map.toList . (.borrowers)) forM_ [(b, from) | (b, (owner, from)) <- lending, owner == root, b /= root] \(b, from) -> report BorrowedObjectUsed at at ("`" <> nameOf root <> "` is borrowed by `" <> nameOf b <> "`, so it cannot be used while `" <> nameOf b <> "` lives") (Just "used here") [Label {span = sp, text = Just "borrowed here"} | Just sp <- [from]] (Just ("use it through `" <> nameOf b <> "`, or after the scope of `" <> nameOf b <> "` ends")) -- an observed owner is read-only while an observer of it lives (SPARK RM 3.10) changing at root = do unusable at root watching <- gets (Map.toList . (.observers)) forM_ [(o, from) | (o, (owner, from)) <- watching, owner == root, o /= root] \(o, from) -> report ObservedObjectChanged at at ("`" <> nameOf root <> "` is observed by `" <> nameOf o <> "`, so it cannot change while `" <> nameOf o <> "` lives") (Just "changed here") [Label {span = sp, text = Just "observed from here"} | Just sp <- [from]] (Just ("change it after the scope of `" <> nameOf o <> "` ends")) -- reading an expression: every part it names must not be moved (comparisons with null -- read only the access value itself) readDeep m e = case e.node of BCompare c | c.right.node == BNull, Just pl <- placeOf c.left -> readPlace False m pl c.left.span BCompare c | c.left.node == BNull, Just pl <- placeOf c.right -> readPlace False m pl c.right.span _ -> case placeOf e of Just pl -> do readPlace True m pl e.span -- indices inside the name are read too mapM_ (readDeep m) (indicesOf e) Nothing -> case e.node of BQuantified q -> mapM_ (readDeep m) [q.low, q.high, q.body] _ -> mapM_ (readDeep m) (subExpressions e) indicesOf e = case e.node of BField f -> indicesOf f.record BIndex ix -> ix.index : indicesOf ix.array BDeref x -> indicesOf x BSlice s -> [s.low, s.high] <> indicesOf s.array BConvert x -> indicesOf x _ -> [] readPlace deep m pl at = do unusable at pl.root forM_ (Map.toList m) \(mv, movedAt) -> when (isPrefixPlace mv pl || (deep && isPrefixPlace pl mv)) do let whole = isPrefixPlace pl mv && mv /= pl report UseAfterMove (Just movedAt) at ( if whole then "`" <> describe pl <> "` is read here, but its part `" <> describe mv <> "` was moved" else "`" <> describe mv <> "` was moved, and is read here" ) (Just "read here") [Label {span = movedAt, text = Just "moved here"}] (Just "assign it a new value before reading it, or read the object it was moved to") returning at m = forM_ (Map.toList m) \(mv, movedAt) -> when (mv.root `elem` returned || roleOf mv.root == Global) do report MovedAtReturn (Just movedAt) at ("`" <> describe mv <> "` is still moved when `" <> sub.name <> "` returns") (Just "returns here") [Label {span = movedAt, text = Just "moved here"}] (Just "give it a new value before returning (`null`, or what it should own)") death at dying m = modify' \st -> st {deaths = DeathPoint {span = at, dying, moved = [k | k <- Map.keys m, k.root `elem` dying]} : st.deaths} calleeModes d = maybe [] (\c -> [r | v <- c.parameters, Just x <- [IntMap.lookup (key v) c.variables], Parameter r <- [x.role]]) (find (\s -> s.decl == d) p.subprograms) lookupMode k modes = case drop k modes of x : _ -> Just x [] -> Nothing -- a part in Ada syntax, its component names from the types on the way describe pl = nameOf pl.root <> Text.concat (go (fmap (.typ) (varOf pl.root)) pl.steps) where go t = \case [] -> [] SField k : rest -> case t of Just (RecordOf r) | f : _ <- drop k r.fields -> ("." <> f.name) : go (Just f.typ) rest _ -> "." : go Nothing rest SIndex : rest -> " (...)" : go (componentOf t) rest -- `P.all.C` is written `P.C` SDeref : rest@(SField _ : _) -> go (designatedOf t) rest SDeref : rest -> ".all" : go (designatedOf t) rest componentOf = \case Just (ArrayOf a) -> Just a.component Just (ArrayValue d) -> Just d.component _ -> Nothing designatedOf = \case Just (AccessOf a) -> Map.lookup a.name p.designated _ -> Nothing -- one report for each move (or place) and code report code reportKey at message primaryText secondary advice = do on <- gets (.reporting) seen <- gets (Set.member (reportKey, code) . (.reported)) when (on && not seen) $ modify' \st -> st { reported = Set.insert (reportKey, code) st.reported , diagnostics = (diagnostic code Flow message) { primary = (\x -> label x (fromMaybe "" primaryText)) <$> at , secondary = secondary , advice } : st.diagnostics } key :: VarId -> Int key (VarId n) = n