WebGPU error handling 5: Move CmdBufBuilder logic to CmdEncoder

This removes the CommandBufferBuilder and copies all the logic into
CommandEncoderBase instead. No changes were done to the logic except for
the implementation of CommandEncoderBase::HandleError and Finish.

BUG=dawn:8

Change-Id: I7b6f44c3cf501477422f067bd277cef470073860
Reviewed-on: https://dawn-review.googlesource.com/c/4820
Reviewed-by: Austin Eng <enga@chromium.org>
Reviewed-by: Kai Ninomiya <kainino@chromium.org>
Commit-Queue: Corentin Wallez <cwallez@chromium.org>
diff --git a/src/dawn_native/CommandBuffer.cpp b/src/dawn_native/CommandBuffer.cpp
index 7986004..7c80939 100644
--- a/src/dawn_native/CommandBuffer.cpp
+++ b/src/dawn_native/CommandBuffer.cpp
@@ -14,294 +14,12 @@
 
 #include "dawn_native/CommandBuffer.h"
 
-#include "dawn_native/BindGroup.h"
-#include "dawn_native/Buffer.h"
-#include "dawn_native/CommandBufferStateTracker.h"
-#include "dawn_native/Commands.h"
-#include "dawn_native/ComputePassEncoder.h"
-#include "dawn_native/ComputePipeline.h"
-#include "dawn_native/Device.h"
-#include "dawn_native/ErrorData.h"
-#include "dawn_native/InputState.h"
-#include "dawn_native/PipelineLayout.h"
-#include "dawn_native/RenderPassDescriptor.h"
-#include "dawn_native/RenderPassEncoder.h"
-#include "dawn_native/RenderPipeline.h"
-#include "dawn_native/Texture.h"
-
-#include <cstring>
-#include <map>
+#include "dawn_native/CommandEncoder.h"
 
 namespace dawn_native {
 
-    namespace {
-
-        MaybeError ValidateCopySizeFitsInTexture(const TextureCopy& textureCopy,
-                                                 const Extent3D& copySize) {
-            const TextureBase* texture = textureCopy.texture.Get();
-            if (textureCopy.level >= texture->GetNumMipLevels()) {
-                return DAWN_VALIDATION_ERROR("Copy mip-level out of range");
-            }
-
-            if (textureCopy.slice >= texture->GetArrayLayers()) {
-                return DAWN_VALIDATION_ERROR("Copy array-layer out of range");
-            }
-
-            // All texture dimensions are in uint32_t so by doing checks in uint64_t we avoid
-            // overflows.
-            uint64_t level = textureCopy.level;
-            if (uint64_t(textureCopy.origin.x) + uint64_t(copySize.width) >
-                    (static_cast<uint64_t>(texture->GetSize().width) >> level) ||
-                uint64_t(textureCopy.origin.y) + uint64_t(copySize.height) >
-                    (static_cast<uint64_t>(texture->GetSize().height) >> level)) {
-                return DAWN_VALIDATION_ERROR("Copy would touch outside of the texture");
-            }
-
-            // TODO(cwallez@chromium.org): Check the depth bound differently for 2D arrays and 3D
-            // textures
-            if (textureCopy.origin.z != 0 || copySize.depth != 1) {
-                return DAWN_VALIDATION_ERROR("No support for z != 0 and depth != 1 for now");
-            }
-
-            return {};
-        }
-
-        bool FitsInBuffer(const BufferBase* buffer, uint32_t offset, uint32_t size) {
-            uint32_t bufferSize = buffer->GetSize();
-            return offset <= bufferSize && (size <= (bufferSize - offset));
-        }
-
-        MaybeError ValidateCopySizeFitsInBuffer(const BufferCopy& bufferCopy, uint32_t dataSize) {
-            if (!FitsInBuffer(bufferCopy.buffer.Get(), bufferCopy.offset, dataSize)) {
-                return DAWN_VALIDATION_ERROR("Copy would overflow the buffer");
-            }
-
-            return {};
-        }
-
-        MaybeError ValidateTexelBufferOffset(TextureBase* texture, const BufferCopy& bufferCopy) {
-            uint32_t texelSize =
-                static_cast<uint32_t>(TextureFormatPixelSize(texture->GetFormat()));
-            if (bufferCopy.offset % texelSize != 0) {
-                return DAWN_VALIDATION_ERROR("Buffer offset must be a multiple of the texel size");
-            }
-
-            return {};
-        }
-
-        MaybeError ValidateImageHeight(uint32_t imageHeight, uint32_t copyHeight) {
-            if (imageHeight < copyHeight) {
-                return DAWN_VALIDATION_ERROR("Image height must not be less than the copy height.");
-            }
-
-            return {};
-        }
-
-        MaybeError ComputeTextureCopyBufferSize(const Extent3D& copySize,
-                                                uint32_t rowPitch,
-                                                uint32_t imageHeight,
-                                                uint32_t* bufferSize) {
-            DAWN_TRY(ValidateImageHeight(imageHeight, copySize.height));
-
-            // TODO(cwallez@chromium.org): check for overflows
-            uint32_t slicePitch = rowPitch * imageHeight;
-            uint32_t sliceSize = rowPitch * (copySize.height - 1) + copySize.width;
-            *bufferSize = (slicePitch * (copySize.depth - 1)) + sliceSize;
-
-            return {};
-        }
-
-        uint32_t ComputeDefaultRowPitch(TextureBase* texture, uint32_t width) {
-            uint32_t texelSize = TextureFormatPixelSize(texture->GetFormat());
-            return texelSize * width;
-        }
-
-        MaybeError ValidateRowPitch(dawn::TextureFormat format,
-                                    const Extent3D& copySize,
-                                    uint32_t rowPitch) {
-            if (rowPitch % kTextureRowPitchAlignment != 0) {
-                return DAWN_VALIDATION_ERROR("Row pitch must be a multiple of 256");
-            }
-
-            uint32_t texelSize = TextureFormatPixelSize(format);
-            if (rowPitch < copySize.width * texelSize) {
-                return DAWN_VALIDATION_ERROR(
-                    "Row pitch must not be less than the number of bytes per row");
-            }
-
-            return {};
-        }
-
-        MaybeError ValidateCanUseAs(BufferBase* buffer, dawn::BufferUsageBit usage) {
-            ASSERT(HasZeroOrOneBits(usage));
-            if (!(buffer->GetUsage() & usage)) {
-                return DAWN_VALIDATION_ERROR("buffer doesn't have the required usage.");
-            }
-
-            return {};
-        }
-
-        MaybeError ValidateCanUseAs(TextureBase* texture, dawn::TextureUsageBit usage) {
-            ASSERT(HasZeroOrOneBits(usage));
-            if (!(texture->GetUsage() & usage)) {
-                return DAWN_VALIDATION_ERROR("texture doesn't have the required usage.");
-            }
-
-            return {};
-        }
-
-        enum class PassType {
-            Render,
-            Compute,
-        };
-
-        // Helper class to encapsulate the logic of tracking per-resource usage during the
-        // validation of command buffer passes. It is used both to know if there are validation
-        // errors, and to get a list of resources used per pass for backends that need the
-        // information.
-        class PassResourceUsageTracker {
-          public:
-            void BufferUsedAs(BufferBase* buffer, dawn::BufferUsageBit usage) {
-                // std::map's operator[] will create the key and return 0 if the key didn't exist
-                // before.
-                dawn::BufferUsageBit& storedUsage = mBufferUsages[buffer];
-
-                if (usage == dawn::BufferUsageBit::Storage &&
-                    storedUsage & dawn::BufferUsageBit::Storage) {
-                    mStorageUsedMultipleTimes = true;
-                }
-
-                storedUsage |= usage;
-            }
-
-            void TextureUsedAs(TextureBase* texture, dawn::TextureUsageBit usage) {
-                // std::map's operator[] will create the key and return 0 if the key didn't exist
-                // before.
-                dawn::TextureUsageBit& storedUsage = mTextureUsages[texture];
-
-                if (usage == dawn::TextureUsageBit::Storage &&
-                    storedUsage & dawn::TextureUsageBit::Storage) {
-                    mStorageUsedMultipleTimes = true;
-                }
-
-                storedUsage |= usage;
-            }
-
-            // Performs the per-pass usage validation checks
-            MaybeError ValidateUsages(PassType pass) const {
-                // Storage resources cannot be used twice in the same compute pass
-                if (pass == PassType::Compute && mStorageUsedMultipleTimes) {
-                    return DAWN_VALIDATION_ERROR(
-                        "Storage resource used multiple times in compute pass");
-                }
-
-                // Buffers can only be used as single-write or multiple read.
-                for (auto& it : mBufferUsages) {
-                    BufferBase* buffer = it.first;
-                    dawn::BufferUsageBit usage = it.second;
-
-                    if (usage & ~buffer->GetUsage()) {
-                        return DAWN_VALIDATION_ERROR("Buffer missing usage for the pass");
-                    }
-
-                    bool readOnly = (usage & kReadOnlyBufferUsages) == usage;
-                    bool singleUse = dawn::HasZeroOrOneBits(usage);
-
-                    if (!readOnly && !singleUse) {
-                        return DAWN_VALIDATION_ERROR(
-                            "Buffer used as writeable usage and another usage in pass");
-                    }
-                }
-
-                // Textures can only be used as single-write or multiple read.
-                // TODO(cwallez@chromium.org): implement per-subresource tracking
-                for (auto& it : mTextureUsages) {
-                    TextureBase* texture = it.first;
-                    dawn::TextureUsageBit usage = it.second;
-
-                    if (usage & ~texture->GetUsage()) {
-                        return DAWN_VALIDATION_ERROR("Texture missing usage for the pass");
-                    }
-
-                    // For textures the only read-only usage in a pass is Sampled, so checking the
-                    // usage constraint simplifies to checking a single usage bit is set.
-                    if (!dawn::HasZeroOrOneBits(it.second)) {
-                        return DAWN_VALIDATION_ERROR(
-                            "Texture used with more than one usage in pass");
-                    }
-                }
-
-                return {};
-            }
-
-            // Returns the per-pass usage for use by backends for APIs with explicit barriers.
-            PassResourceUsage AcquireResourceUsage() {
-                PassResourceUsage result;
-                result.buffers.reserve(mBufferUsages.size());
-                result.bufferUsages.reserve(mBufferUsages.size());
-                result.textures.reserve(mTextureUsages.size());
-                result.textureUsages.reserve(mTextureUsages.size());
-
-                for (auto& it : mBufferUsages) {
-                    result.buffers.push_back(it.first);
-                    result.bufferUsages.push_back(it.second);
-                }
-
-                for (auto& it : mTextureUsages) {
-                    result.textures.push_back(it.first);
-                    result.textureUsages.push_back(it.second);
-                }
-
-                return result;
-            }
-
-          private:
-            std::map<BufferBase*, dawn::BufferUsageBit> mBufferUsages;
-            std::map<TextureBase*, dawn::TextureUsageBit> mTextureUsages;
-            bool mStorageUsedMultipleTimes = false;
-        };
-
-        void TrackBindGroupResourceUsage(BindGroupBase* group, PassResourceUsageTracker* tracker) {
-            const auto& layoutInfo = group->GetLayout()->GetBindingInfo();
-
-            for (uint32_t i : IterateBitSet(layoutInfo.mask)) {
-                dawn::BindingType type = layoutInfo.types[i];
-
-                switch (type) {
-                    case dawn::BindingType::UniformBuffer: {
-                        BufferBase* buffer = group->GetBindingAsBufferBinding(i).buffer;
-                        tracker->BufferUsedAs(buffer, dawn::BufferUsageBit::Uniform);
-                    } break;
-
-                    case dawn::BindingType::StorageBuffer: {
-                        BufferBase* buffer = group->GetBindingAsBufferBinding(i).buffer;
-                        tracker->BufferUsedAs(buffer, dawn::BufferUsageBit::Storage);
-                    } break;
-
-                    case dawn::BindingType::SampledTexture: {
-                        TextureBase* texture = group->GetBindingAsTextureView(i)->GetTexture();
-                        tracker->TextureUsedAs(texture, dawn::TextureUsageBit::Sampled);
-                    } break;
-
-                    case dawn::BindingType::Sampler:
-                        break;
-                }
-            }
-        }
-
-    }  // namespace
-
-    enum class CommandBufferBuilder::EncodingState : uint8_t {
-        TopLevel,
-        ComputePass,
-        RenderPass,
-        Finished
-    };
-
-    // CommandBuffer
-
-    CommandBufferBase::CommandBufferBase(CommandBufferBuilder* builder)
-        : ObjectBase(builder->GetDevice()), mResourceUsages(builder->AcquireResourceUsages()) {
+    CommandBufferBase::CommandBufferBase(DeviceBase* device, CommandEncoderBase* encoder)
+        : ObjectBase(device), mResourceUsages(encoder->AcquireResourceUsages()) {
     }
 
     CommandBufferBase::CommandBufferBase(DeviceBase* device, ObjectBase::ErrorTag tag)
@@ -317,486 +35,4 @@
         return mResourceUsages;
     }
 
-    // CommandBufferBuilder
-
-    CommandBufferBuilder::CommandBufferBuilder(DeviceBase* device)
-        : Builder(device), mEncodingState(EncodingState::TopLevel) {
-    }
-
-    CommandBufferBuilder::~CommandBufferBuilder() {
-        if (!mWereCommandsAcquired) {
-            MoveToIterator();
-            FreeCommands(&mIterator);
-        }
-    }
-
-    CommandIterator CommandBufferBuilder::AcquireCommands() {
-        ASSERT(!mWereCommandsAcquired);
-        mWereCommandsAcquired = true;
-        return std::move(mIterator);
-    }
-
-    CommandBufferResourceUsage CommandBufferBuilder::AcquireResourceUsages() {
-        ASSERT(!mWereResourceUsagesAcquired);
-        mWereResourceUsagesAcquired = true;
-        return std::move(mResourceUsages);
-    }
-
-    CommandBufferBase* CommandBufferBuilder::GetResultImpl() {
-        mEncodingState = EncodingState::Finished;
-
-        MoveToIterator();
-        return GetDevice()->CreateCommandBuffer(this);
-    }
-
-    void CommandBufferBuilder::MoveToIterator() {
-        if (!mWasMovedToIterator) {
-            mIterator = std::move(mAllocator);
-            mWasMovedToIterator = true;
-        }
-    }
-
-    void CommandBufferBuilder::PassEnded() {
-        if (mEncodingState == EncodingState::ComputePass) {
-            mAllocator.Allocate<EndComputePassCmd>(Command::EndComputePass);
-        } else {
-            ASSERT(mEncodingState == EncodingState::RenderPass);
-            mAllocator.Allocate<EndRenderPassCmd>(Command::EndRenderPass);
-        }
-        mEncodingState = EncodingState::TopLevel;
-    }
-
-    void CommandBufferBuilder::ConsumeError(ErrorData* error) {
-        HandleError(error->GetMessage().c_str());
-        delete error;
-    }
-
-    // Implementation of the command buffer validation that can be precomputed before submit
-
-    MaybeError CommandBufferBuilder::ValidateGetResult() {
-        if (mEncodingState != EncodingState::TopLevel) {
-            return DAWN_VALIDATION_ERROR("Command buffer recording ended mid-pass");
-        }
-
-        MoveToIterator();
-        mIterator.Reset();
-
-        Command type;
-        while (mIterator.NextCommandId(&type)) {
-            switch (type) {
-                case Command::BeginComputePass: {
-                    mIterator.NextCommand<BeginComputePassCmd>();
-                    DAWN_TRY(ValidateComputePass());
-                } break;
-
-                case Command::BeginRenderPass: {
-                    BeginRenderPassCmd* cmd = mIterator.NextCommand<BeginRenderPassCmd>();
-                    DAWN_TRY(ValidateRenderPass(cmd));
-                } break;
-
-                case Command::CopyBufferToBuffer: {
-                    CopyBufferToBufferCmd* copy = mIterator.NextCommand<CopyBufferToBufferCmd>();
-
-                    DAWN_TRY(GetDevice()->ValidateObject(copy->source.buffer.Get()));
-                    DAWN_TRY(GetDevice()->ValidateObject(copy->destination.buffer.Get()));
-                    DAWN_TRY(ValidateCopySizeFitsInBuffer(copy->source, copy->size));
-                    DAWN_TRY(ValidateCopySizeFitsInBuffer(copy->destination, copy->size));
-
-                    DAWN_TRY(ValidateCanUseAs(copy->source.buffer.Get(),
-                                              dawn::BufferUsageBit::TransferSrc));
-                    DAWN_TRY(ValidateCanUseAs(copy->destination.buffer.Get(),
-                                              dawn::BufferUsageBit::TransferDst));
-
-                    mResourceUsages.topLevelBuffers.insert(copy->source.buffer.Get());
-                    mResourceUsages.topLevelBuffers.insert(copy->destination.buffer.Get());
-                } break;
-
-                case Command::CopyBufferToTexture: {
-                    CopyBufferToTextureCmd* copy = mIterator.NextCommand<CopyBufferToTextureCmd>();
-
-                    DAWN_TRY(GetDevice()->ValidateObject(copy->source.buffer.Get()));
-                    DAWN_TRY(GetDevice()->ValidateObject(copy->destination.texture.Get()));
-
-                    uint32_t bufferCopySize = 0;
-                    DAWN_TRY(ValidateRowPitch(copy->destination.texture->GetFormat(),
-                                              copy->copySize, copy->source.rowPitch));
-
-                    DAWN_TRY(ComputeTextureCopyBufferSize(copy->copySize, copy->source.rowPitch,
-                                                          copy->source.imageHeight,
-                                                          &bufferCopySize));
-
-                    DAWN_TRY(ValidateCopySizeFitsInTexture(copy->destination, copy->copySize));
-                    DAWN_TRY(ValidateCopySizeFitsInBuffer(copy->source, bufferCopySize));
-                    DAWN_TRY(
-                        ValidateTexelBufferOffset(copy->destination.texture.Get(), copy->source));
-
-                    DAWN_TRY(ValidateCanUseAs(copy->source.buffer.Get(),
-                                              dawn::BufferUsageBit::TransferSrc));
-                    DAWN_TRY(ValidateCanUseAs(copy->destination.texture.Get(),
-                                              dawn::TextureUsageBit::TransferDst));
-
-                    mResourceUsages.topLevelBuffers.insert(copy->source.buffer.Get());
-                    mResourceUsages.topLevelTextures.insert(copy->destination.texture.Get());
-                } break;
-
-                case Command::CopyTextureToBuffer: {
-                    CopyTextureToBufferCmd* copy = mIterator.NextCommand<CopyTextureToBufferCmd>();
-
-                    DAWN_TRY(GetDevice()->ValidateObject(copy->source.texture.Get()));
-                    DAWN_TRY(GetDevice()->ValidateObject(copy->destination.buffer.Get()));
-
-                    uint32_t bufferCopySize = 0;
-                    DAWN_TRY(ValidateRowPitch(copy->source.texture->GetFormat(), copy->copySize,
-                                              copy->destination.rowPitch));
-                    DAWN_TRY(ComputeTextureCopyBufferSize(
-                        copy->copySize, copy->destination.rowPitch, copy->destination.imageHeight,
-                        &bufferCopySize));
-
-                    DAWN_TRY(ValidateCopySizeFitsInTexture(copy->source, copy->copySize));
-                    DAWN_TRY(ValidateCopySizeFitsInBuffer(copy->destination, bufferCopySize));
-                    DAWN_TRY(
-                        ValidateTexelBufferOffset(copy->source.texture.Get(), copy->destination));
-
-                    DAWN_TRY(ValidateCanUseAs(copy->source.texture.Get(),
-                                              dawn::TextureUsageBit::TransferSrc));
-                    DAWN_TRY(ValidateCanUseAs(copy->destination.buffer.Get(),
-                                              dawn::BufferUsageBit::TransferDst));
-
-                    mResourceUsages.topLevelTextures.insert(copy->source.texture.Get());
-                    mResourceUsages.topLevelBuffers.insert(copy->destination.buffer.Get());
-                } break;
-
-                default:
-                    return DAWN_VALIDATION_ERROR("Command disallowed outside of a pass");
-            }
-        }
-
-        return {};
-    }
-
-    MaybeError CommandBufferBuilder::ValidateComputePass() {
-        PassResourceUsageTracker usageTracker;
-        CommandBufferStateTracker persistentState;
-
-        Command type;
-        while (mIterator.NextCommandId(&type)) {
-            switch (type) {
-                case Command::EndComputePass: {
-                    mIterator.NextCommand<EndComputePassCmd>();
-
-                    DAWN_TRY(usageTracker.ValidateUsages(PassType::Compute));
-                    mResourceUsages.perPass.push_back(usageTracker.AcquireResourceUsage());
-                    return {};
-                } break;
-
-                case Command::Dispatch: {
-                    mIterator.NextCommand<DispatchCmd>();
-                    DAWN_TRY(persistentState.ValidateCanDispatch());
-                } break;
-
-                case Command::SetComputePipeline: {
-                    SetComputePipelineCmd* cmd = mIterator.NextCommand<SetComputePipelineCmd>();
-                    ComputePipelineBase* pipeline = cmd->pipeline.Get();
-                    persistentState.SetComputePipeline(pipeline);
-                } break;
-
-                case Command::SetPushConstants: {
-                    SetPushConstantsCmd* cmd = mIterator.NextCommand<SetPushConstantsCmd>();
-                    mIterator.NextData<uint32_t>(cmd->count);
-                    // Validation of count and offset has already been done when the command was
-                    // recorded because it impacts the size of an allocation in the
-                    // CommandAllocator.
-                    if (cmd->stages & ~dawn::ShaderStageBit::Compute) {
-                        return DAWN_VALIDATION_ERROR(
-                            "SetPushConstants stage must be compute or 0 in compute passes");
-                    }
-                } break;
-
-                case Command::SetBindGroup: {
-                    SetBindGroupCmd* cmd = mIterator.NextCommand<SetBindGroupCmd>();
-
-                    TrackBindGroupResourceUsage(cmd->group.Get(), &usageTracker);
-                    persistentState.SetBindGroup(cmd->index, cmd->group.Get());
-                } break;
-
-                default:
-                    return DAWN_VALIDATION_ERROR("Command disallowed inside a compute pass");
-            }
-        }
-
-        UNREACHABLE();
-        return DAWN_VALIDATION_ERROR("Unfinished compute pass");
-    }
-
-    MaybeError CommandBufferBuilder::ValidateRenderPass(BeginRenderPassCmd* renderPass) {
-        PassResourceUsageTracker usageTracker;
-        CommandBufferStateTracker persistentState;
-
-        // Track usage of the render pass attachments
-        for (uint32_t i : IterateBitSet(renderPass->colorAttachmentsSet)) {
-            RenderPassColorAttachmentInfo* colorAttachment = &renderPass->colorAttachments[i];
-            TextureBase* texture = colorAttachment->view->GetTexture();
-            usageTracker.TextureUsedAs(texture, dawn::TextureUsageBit::OutputAttachment);
-        }
-
-        if (renderPass->hasDepthStencilAttachment) {
-            TextureBase* texture = renderPass->depthStencilAttachment.view->GetTexture();
-            usageTracker.TextureUsedAs(texture, dawn::TextureUsageBit::OutputAttachment);
-        }
-
-        Command type;
-        while (mIterator.NextCommandId(&type)) {
-            switch (type) {
-                case Command::EndRenderPass: {
-                    mIterator.NextCommand<EndRenderPassCmd>();
-
-                    DAWN_TRY(usageTracker.ValidateUsages(PassType::Render));
-                    mResourceUsages.perPass.push_back(usageTracker.AcquireResourceUsage());
-                    return {};
-                } break;
-
-                case Command::Draw: {
-                    mIterator.NextCommand<DrawCmd>();
-                    DAWN_TRY(persistentState.ValidateCanDraw());
-                } break;
-
-                case Command::DrawIndexed: {
-                    mIterator.NextCommand<DrawIndexedCmd>();
-                    DAWN_TRY(persistentState.ValidateCanDrawIndexed());
-                } break;
-
-                case Command::SetRenderPipeline: {
-                    SetRenderPipelineCmd* cmd = mIterator.NextCommand<SetRenderPipelineCmd>();
-                    RenderPipelineBase* pipeline = cmd->pipeline.Get();
-
-                    if (!pipeline->IsCompatibleWith(renderPass)) {
-                        return DAWN_VALIDATION_ERROR(
-                            "Pipeline is incompatible with this render pass");
-                    }
-
-                    persistentState.SetRenderPipeline(pipeline);
-                } break;
-
-                case Command::SetPushConstants: {
-                    SetPushConstantsCmd* cmd = mIterator.NextCommand<SetPushConstantsCmd>();
-                    mIterator.NextData<uint32_t>(cmd->count);
-                    // Validation of count and offset has already been done when the command was
-                    // recorded because it impacts the size of an allocation in the
-                    // CommandAllocator.
-                    if (cmd->stages &
-                        ~(dawn::ShaderStageBit::Vertex | dawn::ShaderStageBit::Fragment)) {
-                        return DAWN_VALIDATION_ERROR(
-                            "SetPushConstants stage must be a subset of (vertex|fragment) in "
-                            "render passes");
-                    }
-                } break;
-
-                case Command::SetStencilReference: {
-                    mIterator.NextCommand<SetStencilReferenceCmd>();
-                } break;
-
-                case Command::SetBlendColor: {
-                    mIterator.NextCommand<SetBlendColorCmd>();
-                } break;
-
-                case Command::SetScissorRect: {
-                    mIterator.NextCommand<SetScissorRectCmd>();
-                } break;
-
-                case Command::SetBindGroup: {
-                    SetBindGroupCmd* cmd = mIterator.NextCommand<SetBindGroupCmd>();
-
-                    TrackBindGroupResourceUsage(cmd->group.Get(), &usageTracker);
-                    persistentState.SetBindGroup(cmd->index, cmd->group.Get());
-                } break;
-
-                case Command::SetIndexBuffer: {
-                    SetIndexBufferCmd* cmd = mIterator.NextCommand<SetIndexBufferCmd>();
-
-                    usageTracker.BufferUsedAs(cmd->buffer.Get(), dawn::BufferUsageBit::Index);
-                    persistentState.SetIndexBuffer();
-                } break;
-
-                case Command::SetVertexBuffers: {
-                    SetVertexBuffersCmd* cmd = mIterator.NextCommand<SetVertexBuffersCmd>();
-                    auto buffers = mIterator.NextData<Ref<BufferBase>>(cmd->count);
-                    mIterator.NextData<uint32_t>(cmd->count);
-
-                    for (uint32_t i = 0; i < cmd->count; ++i) {
-                        usageTracker.BufferUsedAs(buffers[i].Get(), dawn::BufferUsageBit::Vertex);
-                    }
-                    persistentState.SetVertexBuffer(cmd->startSlot, cmd->count);
-                } break;
-
-                default:
-                    return DAWN_VALIDATION_ERROR("Command disallowed inside a render pass");
-            }
-        }
-
-        UNREACHABLE();
-        return DAWN_VALIDATION_ERROR("Unfinished render pass");
-    }
-
-    MaybeError CommandBufferBuilder::ValidateCanRecordTopLevelCommands() const {
-        if (mEncodingState != EncodingState::TopLevel) {
-            return DAWN_VALIDATION_ERROR("Command cannot be recorded inside a pass");
-        }
-        return {};
-    }
-
-    // Implementation of the API's command recording methods
-
-    ComputePassEncoderBase* CommandBufferBuilder::BeginComputePass() {
-        if (ConsumedError(ValidateCanRecordTopLevelCommands())) {
-            return nullptr;
-        }
-
-        mAllocator.Allocate<BeginComputePassCmd>(Command::BeginComputePass);
-
-        mEncodingState = EncodingState::ComputePass;
-        return new ComputePassEncoderBase(GetDevice(), this, &mAllocator);
-    }
-
-    RenderPassEncoderBase* CommandBufferBuilder::BeginRenderPass(RenderPassDescriptorBase* info) {
-        if (ConsumedError(ValidateCanRecordTopLevelCommands())) {
-            return nullptr;
-        }
-
-        if (info == nullptr) {
-            HandleError("RenderPassDescriptor cannot be null");
-            return nullptr;
-        }
-
-        BeginRenderPassCmd* cmd = mAllocator.Allocate<BeginRenderPassCmd>(Command::BeginRenderPass);
-        new (cmd) BeginRenderPassCmd;
-
-        for (uint32_t i : IterateBitSet(info->GetColorAttachmentMask())) {
-            const RenderPassColorAttachmentInfo& colorAttachment = info->GetColorAttachment(i);
-            if (colorAttachment.view.Get() != nullptr) {
-                cmd->colorAttachmentsSet.set(i);
-                cmd->colorAttachments[i] = colorAttachment;
-            }
-        }
-
-        cmd->hasDepthStencilAttachment = info->HasDepthStencilAttachment();
-        if (cmd->hasDepthStencilAttachment) {
-            const RenderPassDepthStencilAttachmentInfo& depthStencilAttachment =
-                info->GetDepthStencilAttachment();
-            cmd->depthStencilAttachment = depthStencilAttachment;
-        }
-
-        cmd->width = info->GetWidth();
-        cmd->height = info->GetHeight();
-
-        mEncodingState = EncodingState::RenderPass;
-        return new RenderPassEncoderBase(GetDevice(), this, &mAllocator);
-    }
-
-    void CommandBufferBuilder::CopyBufferToBuffer(BufferBase* source,
-                                                  uint32_t sourceOffset,
-                                                  BufferBase* destination,
-                                                  uint32_t destinationOffset,
-                                                  uint32_t size) {
-        if (ConsumedError(ValidateCanRecordTopLevelCommands())) {
-            return;
-        }
-
-        if (source == nullptr) {
-            HandleError("Source cannot be null");
-            return;
-        }
-
-        if (destination == nullptr) {
-            HandleError("Destination cannot be null");
-            return;
-        }
-
-        CopyBufferToBufferCmd* copy =
-            mAllocator.Allocate<CopyBufferToBufferCmd>(Command::CopyBufferToBuffer);
-        new (copy) CopyBufferToBufferCmd;
-        copy->source.buffer = source;
-        copy->source.offset = sourceOffset;
-        copy->destination.buffer = destination;
-        copy->destination.offset = destinationOffset;
-        copy->size = size;
-    }
-
-    void CommandBufferBuilder::CopyBufferToTexture(const BufferCopyView* source,
-                                                   const TextureCopyView* destination,
-                                                   const Extent3D* copySize) {
-        if (ConsumedError(ValidateCanRecordTopLevelCommands())) {
-            return;
-        }
-
-        if (source->buffer == nullptr) {
-            HandleError("Buffer cannot be null");
-            return;
-        }
-
-        if (destination->texture == nullptr) {
-            HandleError("Texture cannot be null");
-            return;
-        }
-
-        CopyBufferToTextureCmd* copy =
-            mAllocator.Allocate<CopyBufferToTextureCmd>(Command::CopyBufferToTexture);
-        new (copy) CopyBufferToTextureCmd;
-        copy->source.buffer = source->buffer;
-        copy->source.offset = source->offset;
-        copy->destination.texture = destination->texture;
-        copy->destination.origin = destination->origin;
-        copy->copySize = *copySize;
-        copy->destination.level = destination->level;
-        copy->destination.slice = destination->slice;
-        if (source->rowPitch == 0) {
-            copy->source.rowPitch = ComputeDefaultRowPitch(destination->texture, copySize->width);
-        } else {
-            copy->source.rowPitch = source->rowPitch;
-        }
-        if (source->imageHeight == 0) {
-            copy->source.imageHeight = copySize->height;
-        } else {
-            copy->source.imageHeight = source->imageHeight;
-        }
-    }
-
-    void CommandBufferBuilder::CopyTextureToBuffer(const TextureCopyView* source,
-                                                   const BufferCopyView* destination,
-                                                   const Extent3D* copySize) {
-        if (ConsumedError(ValidateCanRecordTopLevelCommands())) {
-            return;
-        }
-
-        if (source->texture == nullptr) {
-            HandleError("Texture cannot be null");
-            return;
-        }
-
-        if (destination->buffer == nullptr) {
-            HandleError("Buffer cannot be null");
-            return;
-        }
-
-        CopyTextureToBufferCmd* copy =
-            mAllocator.Allocate<CopyTextureToBufferCmd>(Command::CopyTextureToBuffer);
-        new (copy) CopyTextureToBufferCmd;
-        copy->source.texture = source->texture;
-        copy->source.origin = source->origin;
-        copy->copySize = *copySize;
-        copy->source.level = source->level;
-        copy->source.slice = source->slice;
-        copy->destination.buffer = destination->buffer;
-        copy->destination.offset = destination->offset;
-        if (destination->rowPitch == 0) {
-            copy->destination.rowPitch = ComputeDefaultRowPitch(source->texture, copySize->width);
-        } else {
-            copy->destination.rowPitch = destination->rowPitch;
-        }
-        if (destination->imageHeight == 0) {
-            copy->destination.imageHeight = copySize->height;
-        } else {
-            copy->destination.imageHeight = destination->imageHeight;
-        }
-    }
-
 }  // namespace dawn_native
diff --git a/src/dawn_native/CommandBuffer.h b/src/dawn_native/CommandBuffer.h
index ecf154c..0a0004a 100644
--- a/src/dawn_native/CommandBuffer.h
+++ b/src/dawn_native/CommandBuffer.h
@@ -17,34 +17,15 @@
 
 #include "dawn_native/dawn_platform.h"
 
-#include "dawn_native/Builder.h"
-#include "dawn_native/CommandAllocator.h"
-#include "dawn_native/Error.h"
+#include "dawn_native/Forward.h"
 #include "dawn_native/ObjectBase.h"
 #include "dawn_native/PassResourceUsage.h"
 
-#include <memory>
-#include <set>
-#include <utility>
-
 namespace dawn_native {
 
-    struct BeginRenderPassCmd;
-
-    class BindGroupBase;
-    class BufferBase;
-    class FramebufferBase;
-    class DeviceBase;
-    class PipelineBase;
-    class RenderPassBase;
-    class TextureBase;
-
-    class CommandBufferBuilder;
-
     class CommandBufferBase : public ObjectBase {
       public:
-        CommandBufferBase(CommandBufferBuilder* builder);
-
+        CommandBufferBase(DeviceBase* device, CommandEncoderBase* encoder);
         static CommandBufferBase* MakeError(DeviceBase* device);
 
         const CommandBufferResourceUsage& GetResourceUsages() const;
@@ -55,67 +36,6 @@
         CommandBufferResourceUsage mResourceUsages;
     };
 
-    class CommandBufferBuilder : public Builder<CommandBufferBase> {
-      public:
-        CommandBufferBuilder(DeviceBase* device);
-        ~CommandBufferBuilder();
-
-        MaybeError ValidateGetResult();
-
-        CommandIterator AcquireCommands();
-        CommandBufferResourceUsage AcquireResourceUsages();
-
-        // Dawn API
-        ComputePassEncoderBase* BeginComputePass();
-        RenderPassEncoderBase* BeginRenderPass(RenderPassDescriptorBase* info);
-        void CopyBufferToBuffer(BufferBase* source,
-                                uint32_t sourceOffset,
-                                BufferBase* destination,
-                                uint32_t destinationOffset,
-                                uint32_t size);
-        void CopyBufferToTexture(const BufferCopyView* source,
-                                 const TextureCopyView* destination,
-                                 const Extent3D* copySize);
-        void CopyTextureToBuffer(const TextureCopyView* source,
-                                 const BufferCopyView* destination,
-                                 const Extent3D* copySize);
-
-        // Functions to interact with the encoders
-        bool ConsumedError(MaybeError maybeError) {
-            if (DAWN_UNLIKELY(maybeError.IsError())) {
-                ConsumeError(maybeError.AcquireError());
-                return true;
-            }
-            return false;
-        }
-
-        void PassEnded();
-
-      private:
-        friend class CommandBufferBase;
-
-        enum class EncodingState : uint8_t;
-        EncodingState mEncodingState;
-
-        CommandBufferBase* GetResultImpl() override;
-        void MoveToIterator();
-
-        MaybeError ValidateComputePass();
-        MaybeError ValidateRenderPass(BeginRenderPassCmd* renderPass);
-
-        MaybeError ValidateCanRecordTopLevelCommands() const;
-
-        void ConsumeError(ErrorData* error);
-
-        CommandAllocator mAllocator;
-        CommandIterator mIterator;
-        bool mWasMovedToIterator = false;
-        bool mWereCommandsAcquired = false;
-
-        bool mWereResourceUsagesAcquired = false;
-        CommandBufferResourceUsage mResourceUsages;
-    };
-
 }  // namespace dawn_native
 
 #endif  // DAWNNATIVE_COMMANDBUFFER_H_
diff --git a/src/dawn_native/CommandBufferStateTracker.h b/src/dawn_native/CommandBufferStateTracker.h
index 2419ded..f2580e4 100644
--- a/src/dawn_native/CommandBufferStateTracker.h
+++ b/src/dawn_native/CommandBufferStateTracker.h
@@ -16,7 +16,8 @@
 #define DAWNNATIVE_COMMANDBUFFERSTATETRACKER_H
 
 #include "common/Constants.h"
-#include "dawn_native/CommandBuffer.h"
+#include "dawn_native/Error.h"
+#include "dawn_native/Forward.h"
 
 #include <array>
 #include <bitset>
diff --git a/src/dawn_native/CommandEncoder.cpp b/src/dawn_native/CommandEncoder.cpp
index 1ccd725..7a5c81d 100644
--- a/src/dawn_native/CommandEncoder.cpp
+++ b/src/dawn_native/CommandEncoder.cpp
@@ -14,32 +14,363 @@
 
 #include "dawn_native/CommandEncoder.h"
 
+#include "common/BitSetIterator.h"
+#include "dawn_native/BindGroup.h"
+#include "dawn_native/Buffer.h"
 #include "dawn_native/CommandBuffer.h"
+#include "dawn_native/CommandBufferStateTracker.h"
+#include "dawn_native/Commands.h"
+#include "dawn_native/ComputePassEncoder.h"
 #include "dawn_native/Device.h"
+#include "dawn_native/ErrorData.h"
+#include "dawn_native/RenderPassDescriptor.h"
+#include "dawn_native/RenderPassEncoder.h"
+#include "dawn_native/RenderPipeline.h"
+
+#include <map>
 
 namespace dawn_native {
 
-    CommandEncoderBase::CommandEncoderBase(DeviceBase* device) : ObjectBase(device) {
-        // Create a builder with an external reference count of 1. We don't use Ref<> because we
-        // want to release the external reference when the encoder is destroyed.
-        mBuilder = GetDevice()->CreateCommandBufferBuilder();
-        mBuilder->SetErrorCallback(
-            HandleBuilderError,
-            static_cast<dawnCallbackUserdata>(reinterpret_cast<uintptr_t>(this)), 0);
+    namespace {
+
+        MaybeError ValidateCopySizeFitsInTexture(const TextureCopy& textureCopy,
+                                                 const Extent3D& copySize) {
+            const TextureBase* texture = textureCopy.texture.Get();
+            if (textureCopy.level >= texture->GetNumMipLevels()) {
+                return DAWN_VALIDATION_ERROR("Copy mip-level out of range");
+            }
+
+            if (textureCopy.slice >= texture->GetArrayLayers()) {
+                return DAWN_VALIDATION_ERROR("Copy array-layer out of range");
+            }
+
+            // All texture dimensions are in uint32_t so by doing checks in uint64_t we avoid
+            // overflows.
+            uint64_t level = textureCopy.level;
+            if (uint64_t(textureCopy.origin.x) + uint64_t(copySize.width) >
+                    (static_cast<uint64_t>(texture->GetSize().width) >> level) ||
+                uint64_t(textureCopy.origin.y) + uint64_t(copySize.height) >
+                    (static_cast<uint64_t>(texture->GetSize().height) >> level)) {
+                return DAWN_VALIDATION_ERROR("Copy would touch outside of the texture");
+            }
+
+            // TODO(cwallez@chromium.org): Check the depth bound differently for 2D arrays and 3D
+            // textures
+            if (textureCopy.origin.z != 0 || copySize.depth != 1) {
+                return DAWN_VALIDATION_ERROR("No support for z != 0 and depth != 1 for now");
+            }
+
+            return {};
+        }
+
+        bool FitsInBuffer(const BufferBase* buffer, uint32_t offset, uint32_t size) {
+            uint32_t bufferSize = buffer->GetSize();
+            return offset <= bufferSize && (size <= (bufferSize - offset));
+        }
+
+        MaybeError ValidateCopySizeFitsInBuffer(const BufferCopy& bufferCopy, uint32_t dataSize) {
+            if (!FitsInBuffer(bufferCopy.buffer.Get(), bufferCopy.offset, dataSize)) {
+                return DAWN_VALIDATION_ERROR("Copy would overflow the buffer");
+            }
+
+            return {};
+        }
+
+        MaybeError ValidateTexelBufferOffset(TextureBase* texture, const BufferCopy& bufferCopy) {
+            uint32_t texelSize =
+                static_cast<uint32_t>(TextureFormatPixelSize(texture->GetFormat()));
+            if (bufferCopy.offset % texelSize != 0) {
+                return DAWN_VALIDATION_ERROR("Buffer offset must be a multiple of the texel size");
+            }
+
+            return {};
+        }
+
+        MaybeError ValidateImageHeight(uint32_t imageHeight, uint32_t copyHeight) {
+            if (imageHeight < copyHeight) {
+                return DAWN_VALIDATION_ERROR("Image height must not be less than the copy height.");
+            }
+
+            return {};
+        }
+
+        MaybeError ComputeTextureCopyBufferSize(const Extent3D& copySize,
+                                                uint32_t rowPitch,
+                                                uint32_t imageHeight,
+                                                uint32_t* bufferSize) {
+            DAWN_TRY(ValidateImageHeight(imageHeight, copySize.height));
+
+            // TODO(cwallez@chromium.org): check for overflows
+            uint32_t slicePitch = rowPitch * imageHeight;
+            uint32_t sliceSize = rowPitch * (copySize.height - 1) + copySize.width;
+            *bufferSize = (slicePitch * (copySize.depth - 1)) + sliceSize;
+
+            return {};
+        }
+
+        uint32_t ComputeDefaultRowPitch(TextureBase* texture, uint32_t width) {
+            uint32_t texelSize = TextureFormatPixelSize(texture->GetFormat());
+            return texelSize * width;
+        }
+
+        MaybeError ValidateRowPitch(dawn::TextureFormat format,
+                                    const Extent3D& copySize,
+                                    uint32_t rowPitch) {
+            if (rowPitch % kTextureRowPitchAlignment != 0) {
+                return DAWN_VALIDATION_ERROR("Row pitch must be a multiple of 256");
+            }
+
+            uint32_t texelSize = TextureFormatPixelSize(format);
+            if (rowPitch < copySize.width * texelSize) {
+                return DAWN_VALIDATION_ERROR(
+                    "Row pitch must not be less than the number of bytes per row");
+            }
+
+            return {};
+        }
+
+        MaybeError ValidateCanUseAs(BufferBase* buffer, dawn::BufferUsageBit usage) {
+            ASSERT(HasZeroOrOneBits(usage));
+            if (!(buffer->GetUsage() & usage)) {
+                return DAWN_VALIDATION_ERROR("buffer doesn't have the required usage.");
+            }
+
+            return {};
+        }
+
+        MaybeError ValidateCanUseAs(TextureBase* texture, dawn::TextureUsageBit usage) {
+            ASSERT(HasZeroOrOneBits(usage));
+            if (!(texture->GetUsage() & usage)) {
+                return DAWN_VALIDATION_ERROR("texture doesn't have the required usage.");
+            }
+
+            return {};
+        }
+
+        enum class PassType {
+            Render,
+            Compute,
+        };
+
+        // Helper class to encapsulate the logic of tracking per-resource usage during the
+        // validation of command buffer passes. It is used both to know if there are validation
+        // errors, and to get a list of resources used per pass for backends that need the
+        // information.
+        class PassResourceUsageTracker {
+          public:
+            void BufferUsedAs(BufferBase* buffer, dawn::BufferUsageBit usage) {
+                // std::map's operator[] will create the key and return 0 if the key didn't exist
+                // before.
+                dawn::BufferUsageBit& storedUsage = mBufferUsages[buffer];
+
+                if (usage == dawn::BufferUsageBit::Storage &&
+                    storedUsage & dawn::BufferUsageBit::Storage) {
+                    mStorageUsedMultipleTimes = true;
+                }
+
+                storedUsage |= usage;
+            }
+
+            void TextureUsedAs(TextureBase* texture, dawn::TextureUsageBit usage) {
+                // std::map's operator[] will create the key and return 0 if the key didn't exist
+                // before.
+                dawn::TextureUsageBit& storedUsage = mTextureUsages[texture];
+
+                if (usage == dawn::TextureUsageBit::Storage &&
+                    storedUsage & dawn::TextureUsageBit::Storage) {
+                    mStorageUsedMultipleTimes = true;
+                }
+
+                storedUsage |= usage;
+            }
+
+            // Performs the per-pass usage validation checks
+            MaybeError ValidateUsages(PassType pass) const {
+                // Storage resources cannot be used twice in the same compute pass
+                if (pass == PassType::Compute && mStorageUsedMultipleTimes) {
+                    return DAWN_VALIDATION_ERROR(
+                        "Storage resource used multiple times in compute pass");
+                }
+
+                // Buffers can only be used as single-write or multiple read.
+                for (auto& it : mBufferUsages) {
+                    BufferBase* buffer = it.first;
+                    dawn::BufferUsageBit usage = it.second;
+
+                    if (usage & ~buffer->GetUsage()) {
+                        return DAWN_VALIDATION_ERROR("Buffer missing usage for the pass");
+                    }
+
+                    bool readOnly = (usage & kReadOnlyBufferUsages) == usage;
+                    bool singleUse = dawn::HasZeroOrOneBits(usage);
+
+                    if (!readOnly && !singleUse) {
+                        return DAWN_VALIDATION_ERROR(
+                            "Buffer used as writeable usage and another usage in pass");
+                    }
+                }
+
+                // Textures can only be used as single-write or multiple read.
+                // TODO(cwallez@chromium.org): implement per-subresource tracking
+                for (auto& it : mTextureUsages) {
+                    TextureBase* texture = it.first;
+                    dawn::TextureUsageBit usage = it.second;
+
+                    if (usage & ~texture->GetUsage()) {
+                        return DAWN_VALIDATION_ERROR("Texture missing usage for the pass");
+                    }
+
+                    // For textures the only read-only usage in a pass is Sampled, so checking the
+                    // usage constraint simplifies to checking a single usage bit is set.
+                    if (!dawn::HasZeroOrOneBits(it.second)) {
+                        return DAWN_VALIDATION_ERROR(
+                            "Texture used with more than one usage in pass");
+                    }
+                }
+
+                return {};
+            }
+
+            // Returns the per-pass usage for use by backends for APIs with explicit barriers.
+            PassResourceUsage AcquireResourceUsage() {
+                PassResourceUsage result;
+                result.buffers.reserve(mBufferUsages.size());
+                result.bufferUsages.reserve(mBufferUsages.size());
+                result.textures.reserve(mTextureUsages.size());
+                result.textureUsages.reserve(mTextureUsages.size());
+
+                for (auto& it : mBufferUsages) {
+                    result.buffers.push_back(it.first);
+                    result.bufferUsages.push_back(it.second);
+                }
+
+                for (auto& it : mTextureUsages) {
+                    result.textures.push_back(it.first);
+                    result.textureUsages.push_back(it.second);
+                }
+
+                return result;
+            }
+
+          private:
+            std::map<BufferBase*, dawn::BufferUsageBit> mBufferUsages;
+            std::map<TextureBase*, dawn::TextureUsageBit> mTextureUsages;
+            bool mStorageUsedMultipleTimes = false;
+        };
+
+        void TrackBindGroupResourceUsage(BindGroupBase* group, PassResourceUsageTracker* tracker) {
+            const auto& layoutInfo = group->GetLayout()->GetBindingInfo();
+
+            for (uint32_t i : IterateBitSet(layoutInfo.mask)) {
+                dawn::BindingType type = layoutInfo.types[i];
+
+                switch (type) {
+                    case dawn::BindingType::UniformBuffer: {
+                        BufferBase* buffer = group->GetBindingAsBufferBinding(i).buffer;
+                        tracker->BufferUsedAs(buffer, dawn::BufferUsageBit::Uniform);
+                    } break;
+
+                    case dawn::BindingType::StorageBuffer: {
+                        BufferBase* buffer = group->GetBindingAsBufferBinding(i).buffer;
+                        tracker->BufferUsedAs(buffer, dawn::BufferUsageBit::Storage);
+                    } break;
+
+                    case dawn::BindingType::SampledTexture: {
+                        TextureBase* texture = group->GetBindingAsTextureView(i)->GetTexture();
+                        tracker->TextureUsedAs(texture, dawn::TextureUsageBit::Sampled);
+                    } break;
+
+                    case dawn::BindingType::Sampler:
+                        break;
+                }
+            }
+        }
+
+    }  // namespace
+
+    enum class CommandEncoderBase::EncodingState : uint8_t {
+        TopLevel,
+        ComputePass,
+        RenderPass,
+        Finished
+    };
+
+    CommandEncoderBase::CommandEncoderBase(DeviceBase* device)
+        : ObjectBase(device), mEncodingState(EncodingState::TopLevel) {
     }
 
     CommandEncoderBase::~CommandEncoderBase() {
-        // Release the single external reference of the builder
-        mBuilder->Release();
-        mBuilder = nullptr;
+        if (!mWereCommandsAcquired) {
+            MoveToIterator();
+            FreeCommands(&mIterator);
+        }
     }
 
+    CommandIterator CommandEncoderBase::AcquireCommands() {
+        ASSERT(!mWereCommandsAcquired);
+        mWereCommandsAcquired = true;
+        return std::move(mIterator);
+    }
+
+    CommandBufferResourceUsage CommandEncoderBase::AcquireResourceUsages() {
+        ASSERT(!mWereResourceUsagesAcquired);
+        mWereResourceUsagesAcquired = true;
+        return std::move(mResourceUsages);
+    }
+
+    void CommandEncoderBase::MoveToIterator() {
+        if (!mWasMovedToIterator) {
+            mIterator = std::move(mAllocator);
+            mWasMovedToIterator = true;
+        }
+    }
+
+    // Implementation of the API's command recording methods
+
     ComputePassEncoderBase* CommandEncoderBase::BeginComputePass() {
-        return mBuilder->BeginComputePass();
+        if (ConsumedError(ValidateCanRecordTopLevelCommands())) {
+            return nullptr;
+        }
+
+        mAllocator.Allocate<BeginComputePassCmd>(Command::BeginComputePass);
+
+        mEncodingState = EncodingState::ComputePass;
+        return new ComputePassEncoderBase(GetDevice(), this, &mAllocator);
     }
 
     RenderPassEncoderBase* CommandEncoderBase::BeginRenderPass(RenderPassDescriptorBase* info) {
-        return mBuilder->BeginRenderPass(info);
+        if (ConsumedError(ValidateCanRecordTopLevelCommands())) {
+            return nullptr;
+        }
+
+        if (info == nullptr) {
+            HandleError("RenderPassDescriptor cannot be null");
+            return nullptr;
+        }
+
+        BeginRenderPassCmd* cmd = mAllocator.Allocate<BeginRenderPassCmd>(Command::BeginRenderPass);
+        new (cmd) BeginRenderPassCmd;
+
+        for (uint32_t i : IterateBitSet(info->GetColorAttachmentMask())) {
+            const RenderPassColorAttachmentInfo& colorAttachment = info->GetColorAttachment(i);
+            if (colorAttachment.view.Get() != nullptr) {
+                cmd->colorAttachmentsSet.set(i);
+                cmd->colorAttachments[i] = colorAttachment;
+            }
+        }
+
+        cmd->hasDepthStencilAttachment = info->HasDepthStencilAttachment();
+        if (cmd->hasDepthStencilAttachment) {
+            const RenderPassDepthStencilAttachmentInfo& depthStencilAttachment =
+                info->GetDepthStencilAttachment();
+            cmd->depthStencilAttachment = depthStencilAttachment;
+        }
+
+        cmd->width = info->GetWidth();
+        cmd->height = info->GetHeight();
+
+        mEncodingState = EncodingState::RenderPass;
+        return new RenderPassEncoderBase(GetDevice(), this, &mAllocator);
     }
 
     void CommandEncoderBase::CopyBufferToBuffer(BufferBase* source,
@@ -47,20 +378,106 @@
                                                 BufferBase* destination,
                                                 uint32_t destinationOffset,
                                                 uint32_t size) {
-        return mBuilder->CopyBufferToBuffer(source, sourceOffset, destination, destinationOffset,
-                                            size);
+        if (ConsumedError(ValidateCanRecordTopLevelCommands())) {
+            return;
+        }
+
+        if (source == nullptr) {
+            HandleError("Source cannot be null");
+            return;
+        }
+
+        if (destination == nullptr) {
+            HandleError("Destination cannot be null");
+            return;
+        }
+
+        CopyBufferToBufferCmd* copy =
+            mAllocator.Allocate<CopyBufferToBufferCmd>(Command::CopyBufferToBuffer);
+        new (copy) CopyBufferToBufferCmd;
+        copy->source.buffer = source;
+        copy->source.offset = sourceOffset;
+        copy->destination.buffer = destination;
+        copy->destination.offset = destinationOffset;
+        copy->size = size;
     }
 
     void CommandEncoderBase::CopyBufferToTexture(const BufferCopyView* source,
                                                  const TextureCopyView* destination,
                                                  const Extent3D* copySize) {
-        return mBuilder->CopyBufferToTexture(source, destination, copySize);
+        if (ConsumedError(ValidateCanRecordTopLevelCommands())) {
+            return;
+        }
+
+        if (source->buffer == nullptr) {
+            HandleError("Buffer cannot be null");
+            return;
+        }
+
+        if (destination->texture == nullptr) {
+            HandleError("Texture cannot be null");
+            return;
+        }
+
+        CopyBufferToTextureCmd* copy =
+            mAllocator.Allocate<CopyBufferToTextureCmd>(Command::CopyBufferToTexture);
+        new (copy) CopyBufferToTextureCmd;
+        copy->source.buffer = source->buffer;
+        copy->source.offset = source->offset;
+        copy->destination.texture = destination->texture;
+        copy->destination.origin = destination->origin;
+        copy->copySize = *copySize;
+        copy->destination.level = destination->level;
+        copy->destination.slice = destination->slice;
+        if (source->rowPitch == 0) {
+            copy->source.rowPitch = ComputeDefaultRowPitch(destination->texture, copySize->width);
+        } else {
+            copy->source.rowPitch = source->rowPitch;
+        }
+        if (source->imageHeight == 0) {
+            copy->source.imageHeight = copySize->height;
+        } else {
+            copy->source.imageHeight = source->imageHeight;
+        }
     }
 
     void CommandEncoderBase::CopyTextureToBuffer(const TextureCopyView* source,
                                                  const BufferCopyView* destination,
                                                  const Extent3D* copySize) {
-        return mBuilder->CopyTextureToBuffer(source, destination, copySize);
+        if (ConsumedError(ValidateCanRecordTopLevelCommands())) {
+            return;
+        }
+
+        if (source->texture == nullptr) {
+            HandleError("Texture cannot be null");
+            return;
+        }
+
+        if (destination->buffer == nullptr) {
+            HandleError("Buffer cannot be null");
+            return;
+        }
+
+        CopyTextureToBufferCmd* copy =
+            mAllocator.Allocate<CopyTextureToBufferCmd>(Command::CopyTextureToBuffer);
+        new (copy) CopyTextureToBufferCmd;
+        copy->source.texture = source->texture;
+        copy->source.origin = source->origin;
+        copy->copySize = *copySize;
+        copy->source.level = source->level;
+        copy->source.slice = source->slice;
+        copy->destination.buffer = destination->buffer;
+        copy->destination.offset = destination->offset;
+        if (destination->rowPitch == 0) {
+            copy->destination.rowPitch = ComputeDefaultRowPitch(source->texture, copySize->width);
+        } else {
+            copy->destination.rowPitch = destination->rowPitch;
+        }
+        if (destination->imageHeight == 0) {
+            copy->destination.imageHeight = copySize->height;
+        } else {
+            copy->destination.imageHeight = destination->imageHeight;
+        }
     }
 
     CommandBufferBase* CommandEncoderBase::Finish() {
@@ -69,35 +486,313 @@
         }
         ASSERT(!IsError());
 
-        CommandBufferBase* result = mBuilder->GetResult();
-        if (result == nullptr) {
-            ASSERT(mGotError);
-            GetDevice()->ConsumedError(DAWN_VALIDATION_ERROR(mErrorMessage));
-            return CommandBufferBase::MakeError(GetDevice());
-        }
+        mEncodingState = EncodingState::Finished;
 
-        ASSERT(result != nullptr);
-        return result;
+        MoveToIterator();
+        return GetDevice()->CreateCommandBuffer(this);
     }
 
+    // Implementation of functions to interact with sub-encoders
+
+    void CommandEncoderBase::HandleError(const char* message) {
+        if (!mGotError) {
+            mGotError = true;
+            mErrorMessage = message;
+        }
+    }
+
+    void CommandEncoderBase::ConsumeError(ErrorData* error) {
+        HandleError(error->GetMessage().c_str());
+        delete error;
+    }
+
+    void CommandEncoderBase::PassEnded() {
+        if (mEncodingState == EncodingState::ComputePass) {
+            mAllocator.Allocate<EndComputePassCmd>(Command::EndComputePass);
+        } else {
+            ASSERT(mEncodingState == EncodingState::RenderPass);
+            mAllocator.Allocate<EndRenderPassCmd>(Command::EndRenderPass);
+        }
+        mEncodingState = EncodingState::TopLevel;
+    }
+
+    // Implementation of the command buffer validation that can be precomputed before submit
+
     MaybeError CommandEncoderBase::ValidateFinish() {
         DAWN_TRY(GetDevice()->ValidateObject(this));
-        DAWN_TRY(mBuilder->ValidateGetResult());
+
+        if (mGotError) {
+            return DAWN_VALIDATION_ERROR(mErrorMessage);
+        }
+
+        if (mEncodingState != EncodingState::TopLevel) {
+            return DAWN_VALIDATION_ERROR("Command buffer recording ended mid-pass");
+        }
+
+        MoveToIterator();
+        mIterator.Reset();
+
+        Command type;
+        while (mIterator.NextCommandId(&type)) {
+            switch (type) {
+                case Command::BeginComputePass: {
+                    mIterator.NextCommand<BeginComputePassCmd>();
+                    DAWN_TRY(ValidateComputePass());
+                } break;
+
+                case Command::BeginRenderPass: {
+                    BeginRenderPassCmd* cmd = mIterator.NextCommand<BeginRenderPassCmd>();
+                    DAWN_TRY(ValidateRenderPass(cmd));
+                } break;
+
+                case Command::CopyBufferToBuffer: {
+                    CopyBufferToBufferCmd* copy = mIterator.NextCommand<CopyBufferToBufferCmd>();
+
+                    DAWN_TRY(GetDevice()->ValidateObject(copy->source.buffer.Get()));
+                    DAWN_TRY(GetDevice()->ValidateObject(copy->destination.buffer.Get()));
+                    DAWN_TRY(ValidateCopySizeFitsInBuffer(copy->source, copy->size));
+                    DAWN_TRY(ValidateCopySizeFitsInBuffer(copy->destination, copy->size));
+
+                    DAWN_TRY(ValidateCanUseAs(copy->source.buffer.Get(),
+                                              dawn::BufferUsageBit::TransferSrc));
+                    DAWN_TRY(ValidateCanUseAs(copy->destination.buffer.Get(),
+                                              dawn::BufferUsageBit::TransferDst));
+
+                    mResourceUsages.topLevelBuffers.insert(copy->source.buffer.Get());
+                    mResourceUsages.topLevelBuffers.insert(copy->destination.buffer.Get());
+                } break;
+
+                case Command::CopyBufferToTexture: {
+                    CopyBufferToTextureCmd* copy = mIterator.NextCommand<CopyBufferToTextureCmd>();
+
+                    DAWN_TRY(GetDevice()->ValidateObject(copy->source.buffer.Get()));
+                    DAWN_TRY(GetDevice()->ValidateObject(copy->destination.texture.Get()));
+
+                    uint32_t bufferCopySize = 0;
+                    DAWN_TRY(ValidateRowPitch(copy->destination.texture->GetFormat(),
+                                              copy->copySize, copy->source.rowPitch));
+
+                    DAWN_TRY(ComputeTextureCopyBufferSize(copy->copySize, copy->source.rowPitch,
+                                                          copy->source.imageHeight,
+                                                          &bufferCopySize));
+
+                    DAWN_TRY(ValidateCopySizeFitsInTexture(copy->destination, copy->copySize));
+                    DAWN_TRY(ValidateCopySizeFitsInBuffer(copy->source, bufferCopySize));
+                    DAWN_TRY(
+                        ValidateTexelBufferOffset(copy->destination.texture.Get(), copy->source));
+
+                    DAWN_TRY(ValidateCanUseAs(copy->source.buffer.Get(),
+                                              dawn::BufferUsageBit::TransferSrc));
+                    DAWN_TRY(ValidateCanUseAs(copy->destination.texture.Get(),
+                                              dawn::TextureUsageBit::TransferDst));
+
+                    mResourceUsages.topLevelBuffers.insert(copy->source.buffer.Get());
+                    mResourceUsages.topLevelTextures.insert(copy->destination.texture.Get());
+                } break;
+
+                case Command::CopyTextureToBuffer: {
+                    CopyTextureToBufferCmd* copy = mIterator.NextCommand<CopyTextureToBufferCmd>();
+
+                    DAWN_TRY(GetDevice()->ValidateObject(copy->source.texture.Get()));
+                    DAWN_TRY(GetDevice()->ValidateObject(copy->destination.buffer.Get()));
+
+                    uint32_t bufferCopySize = 0;
+                    DAWN_TRY(ValidateRowPitch(copy->source.texture->GetFormat(), copy->copySize,
+                                              copy->destination.rowPitch));
+                    DAWN_TRY(ComputeTextureCopyBufferSize(
+                        copy->copySize, copy->destination.rowPitch, copy->destination.imageHeight,
+                        &bufferCopySize));
+
+                    DAWN_TRY(ValidateCopySizeFitsInTexture(copy->source, copy->copySize));
+                    DAWN_TRY(ValidateCopySizeFitsInBuffer(copy->destination, bufferCopySize));
+                    DAWN_TRY(
+                        ValidateTexelBufferOffset(copy->source.texture.Get(), copy->destination));
+
+                    DAWN_TRY(ValidateCanUseAs(copy->source.texture.Get(),
+                                              dawn::TextureUsageBit::TransferSrc));
+                    DAWN_TRY(ValidateCanUseAs(copy->destination.buffer.Get(),
+                                              dawn::BufferUsageBit::TransferDst));
+
+                    mResourceUsages.topLevelTextures.insert(copy->source.texture.Get());
+                    mResourceUsages.topLevelBuffers.insert(copy->destination.buffer.Get());
+                } break;
+
+                default:
+                    return DAWN_VALIDATION_ERROR("Command disallowed outside of a pass");
+            }
+        }
+
         return {};
     }
 
-    // static
-    void CommandEncoderBase::HandleBuilderError(dawnBuilderErrorStatus status,
-                                                const char* message,
-                                                dawnCallbackUserdata userdata1,
-                                                dawnCallbackUserdata) {
-        CommandEncoderBase* self =
-            reinterpret_cast<CommandEncoderBase*>(static_cast<uintptr_t>(userdata1));
+    MaybeError CommandEncoderBase::ValidateComputePass() {
+        PassResourceUsageTracker usageTracker;
+        CommandBufferStateTracker persistentState;
 
-        if (status != DAWN_BUILDER_ERROR_STATUS_SUCCESS && !self->mGotError) {
-            self->mGotError = true;
-            self->mErrorMessage = message;
+        Command type;
+        while (mIterator.NextCommandId(&type)) {
+            switch (type) {
+                case Command::EndComputePass: {
+                    mIterator.NextCommand<EndComputePassCmd>();
+
+                    DAWN_TRY(usageTracker.ValidateUsages(PassType::Compute));
+                    mResourceUsages.perPass.push_back(usageTracker.AcquireResourceUsage());
+                    return {};
+                } break;
+
+                case Command::Dispatch: {
+                    mIterator.NextCommand<DispatchCmd>();
+                    DAWN_TRY(persistentState.ValidateCanDispatch());
+                } break;
+
+                case Command::SetComputePipeline: {
+                    SetComputePipelineCmd* cmd = mIterator.NextCommand<SetComputePipelineCmd>();
+                    ComputePipelineBase* pipeline = cmd->pipeline.Get();
+                    persistentState.SetComputePipeline(pipeline);
+                } break;
+
+                case Command::SetPushConstants: {
+                    SetPushConstantsCmd* cmd = mIterator.NextCommand<SetPushConstantsCmd>();
+                    mIterator.NextData<uint32_t>(cmd->count);
+                    // Validation of count and offset has already been done when the command was
+                    // recorded because it impacts the size of an allocation in the
+                    // CommandAllocator.
+                    if (cmd->stages & ~dawn::ShaderStageBit::Compute) {
+                        return DAWN_VALIDATION_ERROR(
+                            "SetPushConstants stage must be compute or 0 in compute passes");
+                    }
+                } break;
+
+                case Command::SetBindGroup: {
+                    SetBindGroupCmd* cmd = mIterator.NextCommand<SetBindGroupCmd>();
+
+                    TrackBindGroupResourceUsage(cmd->group.Get(), &usageTracker);
+                    persistentState.SetBindGroup(cmd->index, cmd->group.Get());
+                } break;
+
+                default:
+                    return DAWN_VALIDATION_ERROR("Command disallowed inside a compute pass");
+            }
         }
+
+        UNREACHABLE();
+        return DAWN_VALIDATION_ERROR("Unfinished compute pass");
+    }
+
+    MaybeError CommandEncoderBase::ValidateRenderPass(BeginRenderPassCmd* renderPass) {
+        PassResourceUsageTracker usageTracker;
+        CommandBufferStateTracker persistentState;
+
+        // Track usage of the render pass attachments
+        for (uint32_t i : IterateBitSet(renderPass->colorAttachmentsSet)) {
+            RenderPassColorAttachmentInfo* colorAttachment = &renderPass->colorAttachments[i];
+            TextureBase* texture = colorAttachment->view->GetTexture();
+            usageTracker.TextureUsedAs(texture, dawn::TextureUsageBit::OutputAttachment);
+        }
+
+        if (renderPass->hasDepthStencilAttachment) {
+            TextureBase* texture = renderPass->depthStencilAttachment.view->GetTexture();
+            usageTracker.TextureUsedAs(texture, dawn::TextureUsageBit::OutputAttachment);
+        }
+
+        Command type;
+        while (mIterator.NextCommandId(&type)) {
+            switch (type) {
+                case Command::EndRenderPass: {
+                    mIterator.NextCommand<EndRenderPassCmd>();
+
+                    DAWN_TRY(usageTracker.ValidateUsages(PassType::Render));
+                    mResourceUsages.perPass.push_back(usageTracker.AcquireResourceUsage());
+                    return {};
+                } break;
+
+                case Command::Draw: {
+                    mIterator.NextCommand<DrawCmd>();
+                    DAWN_TRY(persistentState.ValidateCanDraw());
+                } break;
+
+                case Command::DrawIndexed: {
+                    mIterator.NextCommand<DrawIndexedCmd>();
+                    DAWN_TRY(persistentState.ValidateCanDrawIndexed());
+                } break;
+
+                case Command::SetRenderPipeline: {
+                    SetRenderPipelineCmd* cmd = mIterator.NextCommand<SetRenderPipelineCmd>();
+                    RenderPipelineBase* pipeline = cmd->pipeline.Get();
+
+                    if (!pipeline->IsCompatibleWith(renderPass)) {
+                        return DAWN_VALIDATION_ERROR(
+                            "Pipeline is incompatible with this render pass");
+                    }
+
+                    persistentState.SetRenderPipeline(pipeline);
+                } break;
+
+                case Command::SetPushConstants: {
+                    SetPushConstantsCmd* cmd = mIterator.NextCommand<SetPushConstantsCmd>();
+                    mIterator.NextData<uint32_t>(cmd->count);
+                    // Validation of count and offset has already been done when the command was
+                    // recorded because it impacts the size of an allocation in the
+                    // CommandAllocator.
+                    if (cmd->stages &
+                        ~(dawn::ShaderStageBit::Vertex | dawn::ShaderStageBit::Fragment)) {
+                        return DAWN_VALIDATION_ERROR(
+                            "SetPushConstants stage must be a subset of (vertex|fragment) in "
+                            "render passes");
+                    }
+                } break;
+
+                case Command::SetStencilReference: {
+                    mIterator.NextCommand<SetStencilReferenceCmd>();
+                } break;
+
+                case Command::SetBlendColor: {
+                    mIterator.NextCommand<SetBlendColorCmd>();
+                } break;
+
+                case Command::SetScissorRect: {
+                    mIterator.NextCommand<SetScissorRectCmd>();
+                } break;
+
+                case Command::SetBindGroup: {
+                    SetBindGroupCmd* cmd = mIterator.NextCommand<SetBindGroupCmd>();
+
+                    TrackBindGroupResourceUsage(cmd->group.Get(), &usageTracker);
+                    persistentState.SetBindGroup(cmd->index, cmd->group.Get());
+                } break;
+
+                case Command::SetIndexBuffer: {
+                    SetIndexBufferCmd* cmd = mIterator.NextCommand<SetIndexBufferCmd>();
+
+                    usageTracker.BufferUsedAs(cmd->buffer.Get(), dawn::BufferUsageBit::Index);
+                    persistentState.SetIndexBuffer();
+                } break;
+
+                case Command::SetVertexBuffers: {
+                    SetVertexBuffersCmd* cmd = mIterator.NextCommand<SetVertexBuffersCmd>();
+                    auto buffers = mIterator.NextData<Ref<BufferBase>>(cmd->count);
+                    mIterator.NextData<uint32_t>(cmd->count);
+
+                    for (uint32_t i = 0; i < cmd->count; ++i) {
+                        usageTracker.BufferUsedAs(buffers[i].Get(), dawn::BufferUsageBit::Vertex);
+                    }
+                    persistentState.SetVertexBuffer(cmd->startSlot, cmd->count);
+                } break;
+
+                default:
+                    return DAWN_VALIDATION_ERROR("Command disallowed inside a render pass");
+            }
+        }
+
+        UNREACHABLE();
+        return DAWN_VALIDATION_ERROR("Unfinished render pass");
+    }
+
+    MaybeError CommandEncoderBase::ValidateCanRecordTopLevelCommands() const {
+        if (mEncodingState != EncodingState::TopLevel) {
+            return DAWN_VALIDATION_ERROR("Command cannot be recorded inside a pass");
+        }
+        return {};
     }
 
 }  // namespace dawn_native
diff --git a/src/dawn_native/CommandEncoder.h b/src/dawn_native/CommandEncoder.h
index c4c7e06..7ff5d1d 100644
--- a/src/dawn_native/CommandEncoder.h
+++ b/src/dawn_native/CommandEncoder.h
@@ -17,13 +17,16 @@
 
 #include "dawn_native/dawn_platform.h"
 
+#include "dawn_native/CommandAllocator.h"
 #include "dawn_native/Error.h"
 #include "dawn_native/ObjectBase.h"
+#include "dawn_native/PassResourceUsage.h"
 
 #include <string>
 
 namespace dawn_native {
 
+    struct BeginRenderPassCmd;
     class CommandBufferBuilder;
 
     // CommandEncoder is temporarily a wrapper around CommandBufferBuilder so the two can coexist
@@ -34,6 +37,9 @@
         CommandEncoderBase(DeviceBase* device);
         ~CommandEncoderBase();
 
+        CommandIterator AcquireCommands();
+        CommandBufferResourceUsage AcquireResourceUsages();
+
         // Dawn API
         ComputePassEncoderBase* BeginComputePass();
         RenderPassEncoderBase* BeginRenderPass(RenderPassDescriptorBase* info);
@@ -50,14 +56,37 @@
                                  const Extent3D* copySize);
         CommandBufferBase* Finish();
 
+        // Functions to interact with the encoders
+        void HandleError(const char* message);
+        void ConsumeError(ErrorData* error);
+        bool ConsumedError(MaybeError maybeError) {
+            if (DAWN_UNLIKELY(maybeError.IsError())) {
+                ConsumeError(maybeError.AcquireError());
+                return true;
+            }
+            return false;
+        }
+
+        void PassEnded();
+
       private:
         MaybeError ValidateFinish();
-        static void HandleBuilderError(dawnBuilderErrorStatus status,
-                                       const char* message,
-                                       dawnCallbackUserdata userdata1,
-                                       dawnCallbackUserdata userdata2);
+        MaybeError ValidateComputePass();
+        MaybeError ValidateRenderPass(BeginRenderPassCmd* renderPass);
+        MaybeError ValidateCanRecordTopLevelCommands() const;
 
-        CommandBufferBuilder* mBuilder = nullptr;
+        enum class EncodingState : uint8_t;
+        EncodingState mEncodingState;
+
+        void MoveToIterator();
+        CommandAllocator mAllocator;
+        CommandIterator mIterator;
+        bool mWasMovedToIterator = false;
+        bool mWereCommandsAcquired = false;
+
+        bool mWereResourceUsagesAcquired = false;
+        CommandBufferResourceUsage mResourceUsages;
+
         bool mGotError = false;
         std::string mErrorMessage;
     };
diff --git a/src/dawn_native/ComputePassEncoder.cpp b/src/dawn_native/ComputePassEncoder.cpp
index 27a31ce..b3c4ed4 100644
--- a/src/dawn_native/ComputePassEncoder.cpp
+++ b/src/dawn_native/ComputePassEncoder.cpp
@@ -14,7 +14,7 @@
 
 #include "dawn_native/ComputePassEncoder.h"
 
-#include "dawn_native/CommandBuffer.h"
+#include "dawn_native/CommandEncoder.h"
 #include "dawn_native/Commands.h"
 #include "dawn_native/ComputePipeline.h"
 #include "dawn_native/Device.h"
@@ -22,13 +22,13 @@
 namespace dawn_native {
 
     ComputePassEncoderBase::ComputePassEncoderBase(DeviceBase* device,
-                                                   CommandBufferBuilder* topLevelBuilder,
+                                                   CommandEncoderBase* topLevelEncoder,
                                                    CommandAllocator* allocator)
-        : ProgrammablePassEncoder(device, topLevelBuilder, allocator) {
+        : ProgrammablePassEncoder(device, topLevelEncoder, allocator) {
     }
 
     void ComputePassEncoderBase::Dispatch(uint32_t x, uint32_t y, uint32_t z) {
-        if (mTopLevelBuilder->ConsumedError(ValidateCanRecordCommands())) {
+        if (mTopLevelEncoder->ConsumedError(ValidateCanRecordCommands())) {
             return;
         }
 
@@ -40,8 +40,8 @@
     }
 
     void ComputePassEncoderBase::SetPipeline(ComputePipelineBase* pipeline) {
-        if (mTopLevelBuilder->ConsumedError(ValidateCanRecordCommands()) ||
-            mTopLevelBuilder->ConsumedError(GetDevice()->ValidateObject(pipeline))) {
+        if (mTopLevelEncoder->ConsumedError(ValidateCanRecordCommands()) ||
+            mTopLevelEncoder->ConsumedError(GetDevice()->ValidateObject(pipeline))) {
             return;
         }
 
diff --git a/src/dawn_native/ComputePassEncoder.h b/src/dawn_native/ComputePassEncoder.h
index 7de4c76..b2acad8 100644
--- a/src/dawn_native/ComputePassEncoder.h
+++ b/src/dawn_native/ComputePassEncoder.h
@@ -21,13 +21,13 @@
 namespace dawn_native {
 
     // This is called ComputePassEncoderBase to match the code generator expectations. Note that it
-    // is a pure frontend type to record in its parent CommandBufferBuilder and never has a backend
+    // is a pure frontend type to record in its parent CommandEncoder and never has a backend
     // implementation.
     // TODO(cwallez@chromium.org): Remove that generator limitation and rename to ComputePassEncoder
     class ComputePassEncoderBase : public ProgrammablePassEncoder {
       public:
         ComputePassEncoderBase(DeviceBase* device,
-                               CommandBufferBuilder* topLevelBuilder,
+                               CommandEncoderBase* topLevelEncoder,
                                CommandAllocator* allocator);
 
         void Dispatch(uint32_t x, uint32_t y, uint32_t z);
diff --git a/src/dawn_native/Device.cpp b/src/dawn_native/Device.cpp
index 48e3398..174b722 100644
--- a/src/dawn_native/Device.cpp
+++ b/src/dawn_native/Device.cpp
@@ -147,9 +147,6 @@
 
         return result;
     }
-    CommandBufferBuilder* DeviceBase::CreateCommandBufferBuilder() {
-        return new CommandBufferBuilder(this);
-    }
     CommandEncoderBase* DeviceBase::CreateCommandEncoder() {
         return new CommandEncoderBase(this);
     }
diff --git a/src/dawn_native/Device.h b/src/dawn_native/Device.h
index 75ebf78..0eb9810 100644
--- a/src/dawn_native/Device.h
+++ b/src/dawn_native/Device.h
@@ -30,6 +30,7 @@
     using ErrorCallback = void (*)(const char* errorMessage, void* userData);
 
     class AdapterBase;
+    class BufferBuilder;
     class FenceSignalTracker;
     class DynamicUploader;
     class StagingBufferBase;
@@ -58,7 +59,7 @@
 
         FenceSignalTracker* GetFenceSignalTracker() const;
 
-        virtual CommandBufferBase* CreateCommandBuffer(CommandBufferBuilder* builder) = 0;
+        virtual CommandBufferBase* CreateCommandBuffer(CommandEncoderBase* encoder) = 0;
         virtual InputStateBase* CreateInputState(InputStateBuilder* builder) = 0;
         virtual RenderPassDescriptorBase* CreateRenderPassDescriptor(
             RenderPassDescriptorBuilder* builder) = 0;
@@ -90,7 +91,6 @@
         BindGroupBase* CreateBindGroup(const BindGroupDescriptor* descriptor);
         BindGroupLayoutBase* CreateBindGroupLayout(const BindGroupLayoutDescriptor* descriptor);
         BufferBase* CreateBuffer(const BufferDescriptor* descriptor);
-        CommandBufferBuilder* CreateCommandBufferBuilder();
         CommandEncoderBase* CreateCommandEncoder();
         ComputePipelineBase* CreateComputePipeline(const ComputePipelineDescriptor* descriptor);
         FenceBase* CreateFence(const FenceDescriptor* descriptor);
diff --git a/src/dawn_native/Forward.h b/src/dawn_native/Forward.h
index 76c12a5..2d1af63 100644
--- a/src/dawn_native/Forward.h
+++ b/src/dawn_native/Forward.h
@@ -21,22 +21,18 @@
 
     class AdapterBase;
     class BindGroupBase;
-    class BindGroupBuilder;
     class BindGroupLayoutBase;
-    class BindGroupLayoutBuilder;
     class BufferBase;
-    class BufferBuilder;
     class ComputePipelineBase;
     class CommandBufferBase;
-    class CommandBufferBuilder;
     class CommandEncoderBase;
     class ComputePassEncoderBase;
     class FenceBase;
     class InputStateBase;
     class InputStateBuilder;
     class InstanceBase;
+    class PipelineBase;
     class PipelineLayoutBase;
-    class PipelineLayoutBuilder;
     class QueueBase;
     class RenderPassDescriptorBase;
     class RenderPassDescriptorBuilder;
@@ -44,13 +40,10 @@
     class RenderPipelineBase;
     class SamplerBase;
     class ShaderModuleBase;
-    class ShaderModuleBuilder;
     class StagingBufferBase;
     class SwapChainBase;
-    class SwapChainBuilder;
     class TextureBase;
     class TextureViewBase;
-    class TextureViewBuilder;
 
     class DeviceBase;
 
diff --git a/src/dawn_native/ProgrammablePassEncoder.cpp b/src/dawn_native/ProgrammablePassEncoder.cpp
index bc9f19e..9f54ce5 100644
--- a/src/dawn_native/ProgrammablePassEncoder.cpp
+++ b/src/dawn_native/ProgrammablePassEncoder.cpp
@@ -24,28 +24,28 @@
 namespace dawn_native {
 
     ProgrammablePassEncoder::ProgrammablePassEncoder(DeviceBase* device,
-                                                     CommandBufferBuilder* topLevelBuilder,
+                                                     CommandEncoderBase* topLevelEncoder,
                                                      CommandAllocator* allocator)
-        : ObjectBase(device), mTopLevelBuilder(topLevelBuilder), mAllocator(allocator) {
+        : ObjectBase(device), mTopLevelEncoder(topLevelEncoder), mAllocator(allocator) {
     }
 
     void ProgrammablePassEncoder::EndPass() {
-        if (mTopLevelBuilder->ConsumedError(ValidateCanRecordCommands())) {
+        if (mTopLevelEncoder->ConsumedError(ValidateCanRecordCommands())) {
             return;
         }
 
-        mTopLevelBuilder->PassEnded();
+        mTopLevelEncoder->PassEnded();
         mAllocator = nullptr;
     }
 
     void ProgrammablePassEncoder::SetBindGroup(uint32_t groupIndex, BindGroupBase* group) {
-        if (mTopLevelBuilder->ConsumedError(ValidateCanRecordCommands()) ||
-            mTopLevelBuilder->ConsumedError(GetDevice()->ValidateObject(group))) {
+        if (mTopLevelEncoder->ConsumedError(ValidateCanRecordCommands()) ||
+            mTopLevelEncoder->ConsumedError(GetDevice()->ValidateObject(group))) {
             return;
         }
 
         if (groupIndex >= kMaxBindGroups) {
-            mTopLevelBuilder->HandleError("Setting bind group over the max");
+            mTopLevelEncoder->HandleError("Setting bind group over the max");
             return;
         }
 
@@ -59,13 +59,13 @@
                                                    uint32_t offset,
                                                    uint32_t count,
                                                    const void* data) {
-        if (mTopLevelBuilder->ConsumedError(ValidateCanRecordCommands())) {
+        if (mTopLevelEncoder->ConsumedError(ValidateCanRecordCommands())) {
             return;
         }
 
         // TODO(cwallez@chromium.org): check for overflows
         if (offset + count > kMaxPushConstants) {
-            mTopLevelBuilder->HandleError("Setting too many push constants");
+            mTopLevelEncoder->HandleError("Setting too many push constants");
             return;
         }
 
diff --git a/src/dawn_native/ProgrammablePassEncoder.h b/src/dawn_native/ProgrammablePassEncoder.h
index 2606096..c082dc0 100644
--- a/src/dawn_native/ProgrammablePassEncoder.h
+++ b/src/dawn_native/ProgrammablePassEncoder.h
@@ -15,6 +15,7 @@
 #ifndef DAWNNATIVE_PROGRAMMABLEPASSENCODER_H_
 #define DAWNNATIVE_PROGRAMMABLEPASSENCODER_H_
 
+#include "dawn_native/CommandEncoder.h"
 #include "dawn_native/Error.h"
 #include "dawn_native/ObjectBase.h"
 
@@ -29,7 +30,7 @@
     class ProgrammablePassEncoder : public ObjectBase {
       public:
         ProgrammablePassEncoder(DeviceBase* device,
-                                CommandBufferBuilder* topLevelBuilder,
+                                CommandEncoderBase* topLevelEncoder,
                                 CommandAllocator* allocator);
 
         void EndPass();
@@ -43,9 +44,9 @@
       protected:
         MaybeError ValidateCanRecordCommands() const;
 
-        // The allocator is borrowed from the top level builder. Keep a reference to the builder
+        // The allocator is borrowed from the top level encoder. Keep a reference to the encoder
         // to make sure the allocator isn't freed.
-        Ref<CommandBufferBuilder> mTopLevelBuilder = nullptr;
+        Ref<CommandEncoderBase> mTopLevelEncoder = nullptr;
         // mAllocator is cleared at the end of the pass so it acts as a tag that EndPass was called
         CommandAllocator* mAllocator = nullptr;
     };
diff --git a/src/dawn_native/RenderPassEncoder.cpp b/src/dawn_native/RenderPassEncoder.cpp
index c392bb3..214b1cd 100644
--- a/src/dawn_native/RenderPassEncoder.cpp
+++ b/src/dawn_native/RenderPassEncoder.cpp
@@ -15,7 +15,7 @@
 #include "dawn_native/RenderPassEncoder.h"
 
 #include "dawn_native/Buffer.h"
-#include "dawn_native/CommandBuffer.h"
+#include "dawn_native/CommandEncoder.h"
 #include "dawn_native/Commands.h"
 #include "dawn_native/Device.h"
 #include "dawn_native/RenderPipeline.h"
@@ -25,16 +25,16 @@
 namespace dawn_native {
 
     RenderPassEncoderBase::RenderPassEncoderBase(DeviceBase* device,
-                                                 CommandBufferBuilder* topLevelBuilder,
+                                                 CommandEncoderBase* topLevelEncoder,
                                                  CommandAllocator* allocator)
-        : ProgrammablePassEncoder(device, topLevelBuilder, allocator) {
+        : ProgrammablePassEncoder(device, topLevelEncoder, allocator) {
     }
 
     void RenderPassEncoderBase::Draw(uint32_t vertexCount,
                                      uint32_t instanceCount,
                                      uint32_t firstVertex,
                                      uint32_t firstInstance) {
-        if (mTopLevelBuilder->ConsumedError(ValidateCanRecordCommands())) {
+        if (mTopLevelEncoder->ConsumedError(ValidateCanRecordCommands())) {
             return;
         }
 
@@ -51,7 +51,7 @@
                                             uint32_t firstIndex,
                                             uint32_t baseVertex,
                                             uint32_t firstInstance) {
-        if (mTopLevelBuilder->ConsumedError(ValidateCanRecordCommands())) {
+        if (mTopLevelEncoder->ConsumedError(ValidateCanRecordCommands())) {
             return;
         }
 
@@ -65,8 +65,8 @@
     }
 
     void RenderPassEncoderBase::SetPipeline(RenderPipelineBase* pipeline) {
-        if (mTopLevelBuilder->ConsumedError(ValidateCanRecordCommands()) ||
-            mTopLevelBuilder->ConsumedError(GetDevice()->ValidateObject(pipeline))) {
+        if (mTopLevelEncoder->ConsumedError(ValidateCanRecordCommands()) ||
+            mTopLevelEncoder->ConsumedError(GetDevice()->ValidateObject(pipeline))) {
             return;
         }
 
@@ -77,7 +77,7 @@
     }
 
     void RenderPassEncoderBase::SetStencilReference(uint32_t reference) {
-        if (mTopLevelBuilder->ConsumedError(ValidateCanRecordCommands())) {
+        if (mTopLevelEncoder->ConsumedError(ValidateCanRecordCommands())) {
             return;
         }
 
@@ -88,7 +88,7 @@
     }
 
     void RenderPassEncoderBase::SetBlendColor(const Color* color) {
-        if (mTopLevelBuilder->ConsumedError(ValidateCanRecordCommands())) {
+        if (mTopLevelEncoder->ConsumedError(ValidateCanRecordCommands())) {
             return;
         }
 
@@ -101,7 +101,7 @@
                                                uint32_t y,
                                                uint32_t width,
                                                uint32_t height) {
-        if (mTopLevelBuilder->ConsumedError(ValidateCanRecordCommands())) {
+        if (mTopLevelEncoder->ConsumedError(ValidateCanRecordCommands())) {
             return;
         }
 
@@ -114,8 +114,8 @@
     }
 
     void RenderPassEncoderBase::SetIndexBuffer(BufferBase* buffer, uint32_t offset) {
-        if (mTopLevelBuilder->ConsumedError(ValidateCanRecordCommands()) ||
-            mTopLevelBuilder->ConsumedError(GetDevice()->ValidateObject(buffer))) {
+        if (mTopLevelEncoder->ConsumedError(ValidateCanRecordCommands()) ||
+            mTopLevelEncoder->ConsumedError(GetDevice()->ValidateObject(buffer))) {
             return;
         }
 
@@ -129,12 +129,12 @@
                                                  uint32_t count,
                                                  BufferBase* const* buffers,
                                                  uint32_t const* offsets) {
-        if (mTopLevelBuilder->ConsumedError(ValidateCanRecordCommands())) {
+        if (mTopLevelEncoder->ConsumedError(ValidateCanRecordCommands())) {
             return;
         }
 
         for (size_t i = 0; i < count; ++i) {
-            if (mTopLevelBuilder->ConsumedError(GetDevice()->ValidateObject(buffers[i]))) {
+            if (mTopLevelEncoder->ConsumedError(GetDevice()->ValidateObject(buffers[i]))) {
                 return;
             }
         }
diff --git a/src/dawn_native/RenderPassEncoder.h b/src/dawn_native/RenderPassEncoder.h
index 3e7e415..08547a6 100644
--- a/src/dawn_native/RenderPassEncoder.h
+++ b/src/dawn_native/RenderPassEncoder.h
@@ -21,13 +21,13 @@
 namespace dawn_native {
 
     // This is called RenderPassEncoderBase to match the code generator expectations. Note that it
-    // is a pure frontend type to record in its parent CommandBufferBuilder and never has a backend
+    // is a pure frontend type to record in its parent CommandEncoder and never has a backend
     // implementation.
     // TODO(cwallez@chromium.org): Remove that generator limitation and rename to ComputePassEncoder
     class RenderPassEncoderBase : public ProgrammablePassEncoder {
       public:
         RenderPassEncoderBase(DeviceBase* device,
-                              CommandBufferBuilder* topLevelBuilder,
+                              CommandEncoderBase* topLevelEncoder,
                               CommandAllocator* allocator);
 
         void Draw(uint32_t vertexCount,
diff --git a/src/dawn_native/d3d12/CommandBufferD3D12.cpp b/src/dawn_native/d3d12/CommandBufferD3D12.cpp
index bfaf19a..d11be87 100644
--- a/src/dawn_native/d3d12/CommandBufferD3D12.cpp
+++ b/src/dawn_native/d3d12/CommandBufferD3D12.cpp
@@ -15,6 +15,7 @@
 #include "dawn_native/d3d12/CommandBufferD3D12.h"
 
 #include "common/Assert.h"
+#include "dawn_native/CommandEncoder.h"
 #include "dawn_native/Commands.h"
 #include "dawn_native/d3d12/BindGroupD3D12.h"
 #include "dawn_native/d3d12/BindGroupLayoutD3D12.h"
@@ -322,8 +323,8 @@
 
     }  // anonymous namespace
 
-    CommandBuffer::CommandBuffer(CommandBufferBuilder* builder)
-        : CommandBufferBase(builder), mCommands(builder->AcquireCommands()) {
+    CommandBuffer::CommandBuffer(Device* device, CommandEncoderBase* encoder)
+        : CommandBufferBase(device, encoder), mCommands(encoder->AcquireCommands()) {
     }
 
     CommandBuffer::~CommandBuffer() {
diff --git a/src/dawn_native/d3d12/CommandBufferD3D12.h b/src/dawn_native/d3d12/CommandBufferD3D12.h
index 60d2fc7..e7aee32 100644
--- a/src/dawn_native/d3d12/CommandBufferD3D12.h
+++ b/src/dawn_native/d3d12/CommandBufferD3D12.h
@@ -46,7 +46,7 @@
 
     class CommandBuffer : public CommandBufferBase {
       public:
-        CommandBuffer(CommandBufferBuilder* builder);
+        CommandBuffer(Device* device, CommandEncoderBase* encoder);
         ~CommandBuffer();
 
         void RecordCommands(ComPtr<ID3D12GraphicsCommandList> commandList, uint32_t indexInSubmit);
diff --git a/src/dawn_native/d3d12/DeviceD3D12.cpp b/src/dawn_native/d3d12/DeviceD3D12.cpp
index 593aaf8..5297f3f 100644
--- a/src/dawn_native/d3d12/DeviceD3D12.cpp
+++ b/src/dawn_native/d3d12/DeviceD3D12.cpp
@@ -210,8 +210,8 @@
     ResultOrError<BufferBase*> Device::CreateBufferImpl(const BufferDescriptor* descriptor) {
         return new Buffer(this, descriptor);
     }
-    CommandBufferBase* Device::CreateCommandBuffer(CommandBufferBuilder* builder) {
-        return new CommandBuffer(builder);
+    CommandBufferBase* Device::CreateCommandBuffer(CommandEncoderBase* encoder) {
+        return new CommandBuffer(this, encoder);
     }
     ResultOrError<ComputePipelineBase*> Device::CreateComputePipelineImpl(
         const ComputePipelineDescriptor* descriptor) {
diff --git a/src/dawn_native/d3d12/DeviceD3D12.h b/src/dawn_native/d3d12/DeviceD3D12.h
index 2d753d1..ef1950c 100644
--- a/src/dawn_native/d3d12/DeviceD3D12.h
+++ b/src/dawn_native/d3d12/DeviceD3D12.h
@@ -40,7 +40,7 @@
         Device(Adapter* adapter, ComPtr<ID3D12Device> d3d12Device);
         ~Device();
 
-        CommandBufferBase* CreateCommandBuffer(CommandBufferBuilder* builder) override;
+        CommandBufferBase* CreateCommandBuffer(CommandEncoderBase* encoder) override;
         InputStateBase* CreateInputState(InputStateBuilder* builder) override;
         RenderPassDescriptorBase* CreateRenderPassDescriptor(
             RenderPassDescriptorBuilder* builder) override;
diff --git a/src/dawn_native/metal/CommandBufferMTL.h b/src/dawn_native/metal/CommandBufferMTL.h
index c11ab78..89420b8 100644
--- a/src/dawn_native/metal/CommandBufferMTL.h
+++ b/src/dawn_native/metal/CommandBufferMTL.h
@@ -15,12 +15,14 @@
 #ifndef DAWNNATIVE_METAL_COMMANDBUFFERMTL_H_
 #define DAWNNATIVE_METAL_COMMANDBUFFERMTL_H_
 
+#include "dawn_native/CommandAllocator.h"
 #include "dawn_native/CommandBuffer.h"
 
 #import <Metal/Metal.h>
 
 namespace dawn_native {
     struct BeginRenderPassCmd;
+    class CommandEncoderBase;
 }
 
 namespace dawn_native { namespace metal {
@@ -29,7 +31,7 @@
 
     class CommandBuffer : public CommandBufferBase {
       public:
-        CommandBuffer(CommandBufferBuilder* builder);
+        CommandBuffer(Device* device, CommandEncoderBase* encoder);
         ~CommandBuffer();
 
         void FillCommands(id<MTLCommandBuffer> commandBuffer);
@@ -38,7 +40,6 @@
         void EncodeComputePass(id<MTLCommandBuffer> commandBuffer);
         void EncodeRenderPass(id<MTLCommandBuffer> commandBuffer, BeginRenderPassCmd* renderPass);
 
-        Device* mDevice;
         CommandIterator mCommands;
     };
 
diff --git a/src/dawn_native/metal/CommandBufferMTL.mm b/src/dawn_native/metal/CommandBufferMTL.mm
index c90ee5c..f6bc3ee 100644
--- a/src/dawn_native/metal/CommandBufferMTL.mm
+++ b/src/dawn_native/metal/CommandBufferMTL.mm
@@ -15,6 +15,7 @@
 #include "dawn_native/metal/CommandBufferMTL.h"
 
 #include "dawn_native/BindGroup.h"
+#include "dawn_native/CommandEncoder.h"
 #include "dawn_native/Commands.h"
 #include "dawn_native/metal/BufferMTL.h"
 #include "dawn_native/metal/ComputePipelineMTL.h"
@@ -204,10 +205,8 @@
 
     }  // anonymous namespace
 
-    CommandBuffer::CommandBuffer(CommandBufferBuilder* builder)
-        : CommandBufferBase(builder),
-          mDevice(ToBackend(builder->GetDevice())),
-          mCommands(builder->AcquireCommands()) {
+    CommandBuffer::CommandBuffer(Device* device, CommandEncoderBase* encoder)
+        : CommandBufferBase(device, encoder), mCommands(encoder->AcquireCommands()) {
     }
 
     CommandBuffer::~CommandBuffer() {
diff --git a/src/dawn_native/metal/DeviceMTL.h b/src/dawn_native/metal/DeviceMTL.h
index cd45168..5d1e1df 100644
--- a/src/dawn_native/metal/DeviceMTL.h
+++ b/src/dawn_native/metal/DeviceMTL.h
@@ -36,7 +36,7 @@
         Device(AdapterBase* adapter, id<MTLDevice> mtlDevice);
         ~Device();
 
-        CommandBufferBase* CreateCommandBuffer(CommandBufferBuilder* builder) override;
+        CommandBufferBase* CreateCommandBuffer(CommandEncoderBase* encoder) override;
         InputStateBase* CreateInputState(InputStateBuilder* builder) override;
         RenderPassDescriptorBase* CreateRenderPassDescriptor(
             RenderPassDescriptorBuilder* builder) override;
diff --git a/src/dawn_native/metal/DeviceMTL.mm b/src/dawn_native/metal/DeviceMTL.mm
index 2623011..0a07d75 100644
--- a/src/dawn_native/metal/DeviceMTL.mm
+++ b/src/dawn_native/metal/DeviceMTL.mm
@@ -77,8 +77,8 @@
     ResultOrError<BufferBase*> Device::CreateBufferImpl(const BufferDescriptor* descriptor) {
         return new Buffer(this, descriptor);
     }
-    CommandBufferBase* Device::CreateCommandBuffer(CommandBufferBuilder* builder) {
-        return new CommandBuffer(builder);
+    CommandBufferBase* Device::CreateCommandBuffer(CommandEncoderBase* encoder) {
+        return new CommandBuffer(this, encoder);
     }
     ResultOrError<ComputePipelineBase*> Device::CreateComputePipelineImpl(
         const ComputePipelineDescriptor* descriptor) {
diff --git a/src/dawn_native/null/DeviceNull.cpp b/src/dawn_native/null/DeviceNull.cpp
index 338d581..50b5216 100644
--- a/src/dawn_native/null/DeviceNull.cpp
+++ b/src/dawn_native/null/DeviceNull.cpp
@@ -75,8 +75,8 @@
     ResultOrError<BufferBase*> Device::CreateBufferImpl(const BufferDescriptor* descriptor) {
         return new Buffer(this, descriptor);
     }
-    CommandBufferBase* Device::CreateCommandBuffer(CommandBufferBuilder* builder) {
-        return new CommandBuffer(builder);
+    CommandBufferBase* Device::CreateCommandBuffer(CommandEncoderBase* encoder) {
+        return new CommandBuffer(this, encoder);
     }
     ResultOrError<ComputePipelineBase*> Device::CreateComputePipelineImpl(
         const ComputePipelineDescriptor* descriptor) {
@@ -232,8 +232,8 @@
 
     // CommandBuffer
 
-    CommandBuffer::CommandBuffer(CommandBufferBuilder* builder)
-        : CommandBufferBase(builder), mCommands(builder->AcquireCommands()) {
+    CommandBuffer::CommandBuffer(Device* device, CommandEncoderBase* encoder)
+        : CommandBufferBase(device, encoder), mCommands(encoder->AcquireCommands()) {
     }
 
     CommandBuffer::~CommandBuffer() {
diff --git a/src/dawn_native/null/DeviceNull.h b/src/dawn_native/null/DeviceNull.h
index 052a624..2107e3a 100644
--- a/src/dawn_native/null/DeviceNull.h
+++ b/src/dawn_native/null/DeviceNull.h
@@ -19,6 +19,7 @@
 #include "dawn_native/BindGroupLayout.h"
 #include "dawn_native/Buffer.h"
 #include "dawn_native/CommandBuffer.h"
+#include "dawn_native/CommandEncoder.h"
 #include "dawn_native/ComputePipeline.h"
 #include "dawn_native/Device.h"
 #include "dawn_native/InputState.h"
@@ -90,7 +91,7 @@
         Device(Adapter* adapter);
         ~Device();
 
-        CommandBufferBase* CreateCommandBuffer(CommandBufferBuilder* builder) override;
+        CommandBufferBase* CreateCommandBuffer(CommandEncoderBase* encoder) override;
         InputStateBase* CreateInputState(InputStateBuilder* builder) override;
         RenderPassDescriptorBase* CreateRenderPassDescriptor(
             RenderPassDescriptorBuilder* builder) override;
@@ -158,7 +159,7 @@
 
     class CommandBuffer : public CommandBufferBase {
       public:
-        CommandBuffer(CommandBufferBuilder* builder);
+        CommandBuffer(Device* device, CommandEncoderBase* encoder);
         ~CommandBuffer();
 
       private:
diff --git a/src/dawn_native/opengl/CommandBufferGL.cpp b/src/dawn_native/opengl/CommandBufferGL.cpp
index 2f672d8..d86be64 100644
--- a/src/dawn_native/opengl/CommandBufferGL.cpp
+++ b/src/dawn_native/opengl/CommandBufferGL.cpp
@@ -15,9 +15,11 @@
 #include "dawn_native/opengl/CommandBufferGL.h"
 
 #include "dawn_native/BindGroup.h"
+#include "dawn_native/CommandEncoder.h"
 #include "dawn_native/Commands.h"
 #include "dawn_native/opengl/BufferGL.h"
 #include "dawn_native/opengl/ComputePipelineGL.h"
+#include "dawn_native/opengl/DeviceGL.h"
 #include "dawn_native/opengl/Forward.h"
 #include "dawn_native/opengl/InputStateGL.h"
 #include "dawn_native/opengl/PersistentPipelineStateGL.h"
@@ -281,8 +283,8 @@
         }
     }  // namespace
 
-    CommandBuffer::CommandBuffer(CommandBufferBuilder* builder)
-        : CommandBufferBase(builder), mCommands(builder->AcquireCommands()) {
+    CommandBuffer::CommandBuffer(Device* device, CommandEncoderBase* encoder)
+        : CommandBufferBase(device, encoder), mCommands(encoder->AcquireCommands()) {
     }
 
     CommandBuffer::~CommandBuffer() {
diff --git a/src/dawn_native/opengl/CommandBufferGL.h b/src/dawn_native/opengl/CommandBufferGL.h
index 8ba754a..983f0b5 100644
--- a/src/dawn_native/opengl/CommandBufferGL.h
+++ b/src/dawn_native/opengl/CommandBufferGL.h
@@ -28,7 +28,7 @@
 
     class CommandBuffer : public CommandBufferBase {
       public:
-        CommandBuffer(CommandBufferBuilder* builder);
+        CommandBuffer(Device* device, CommandEncoderBase* encoder);
         ~CommandBuffer();
 
         void Execute();
diff --git a/src/dawn_native/opengl/DeviceGL.cpp b/src/dawn_native/opengl/DeviceGL.cpp
index dd0f262..34d2737 100644
--- a/src/dawn_native/opengl/DeviceGL.cpp
+++ b/src/dawn_native/opengl/DeviceGL.cpp
@@ -61,8 +61,8 @@
     ResultOrError<BufferBase*> Device::CreateBufferImpl(const BufferDescriptor* descriptor) {
         return new Buffer(this, descriptor);
     }
-    CommandBufferBase* Device::CreateCommandBuffer(CommandBufferBuilder* builder) {
-        return new CommandBuffer(builder);
+    CommandBufferBase* Device::CreateCommandBuffer(CommandEncoderBase* encoder) {
+        return new CommandBuffer(this, encoder);
     }
     ResultOrError<ComputePipelineBase*> Device::CreateComputePipelineImpl(
         const ComputePipelineDescriptor* descriptor) {
diff --git a/src/dawn_native/opengl/DeviceGL.h b/src/dawn_native/opengl/DeviceGL.h
index fc3716e..e66981e 100644
--- a/src/dawn_native/opengl/DeviceGL.h
+++ b/src/dawn_native/opengl/DeviceGL.h
@@ -40,7 +40,7 @@
         void SubmitFenceSync();
 
         // Dawn API
-        CommandBufferBase* CreateCommandBuffer(CommandBufferBuilder* builder) override;
+        CommandBufferBase* CreateCommandBuffer(CommandEncoderBase* encoder) override;
         InputStateBase* CreateInputState(InputStateBuilder* builder) override;
         RenderPassDescriptorBase* CreateRenderPassDescriptor(
             RenderPassDescriptorBuilder* builder) override;
diff --git a/src/dawn_native/vulkan/CommandBufferVk.cpp b/src/dawn_native/vulkan/CommandBufferVk.cpp
index 462fb26..13107dd 100644
--- a/src/dawn_native/vulkan/CommandBufferVk.cpp
+++ b/src/dawn_native/vulkan/CommandBufferVk.cpp
@@ -14,6 +14,7 @@
 
 #include "dawn_native/vulkan/CommandBufferVk.h"
 
+#include "dawn_native/CommandEncoder.h"
 #include "dawn_native/Commands.h"
 #include "dawn_native/vulkan/BindGroupVk.h"
 #include "dawn_native/vulkan/BufferVk.h"
@@ -205,8 +206,8 @@
         }
     }  // anonymous namespace
 
-    CommandBuffer::CommandBuffer(CommandBufferBuilder* builder)
-        : CommandBufferBase(builder), mCommands(builder->AcquireCommands()) {
+    CommandBuffer::CommandBuffer(Device* device, CommandEncoderBase* encoder)
+        : CommandBufferBase(device, encoder), mCommands(encoder->AcquireCommands()) {
     }
 
     CommandBuffer::~CommandBuffer() {
diff --git a/src/dawn_native/vulkan/CommandBufferVk.h b/src/dawn_native/vulkan/CommandBufferVk.h
index b14f586..df6499d 100644
--- a/src/dawn_native/vulkan/CommandBufferVk.h
+++ b/src/dawn_native/vulkan/CommandBufferVk.h
@@ -15,6 +15,7 @@
 #ifndef DAWNNATIVE_VULKAN_COMMANDBUFFERVK_H_
 #define DAWNNATIVE_VULKAN_COMMANDBUFFERVK_H_
 
+#include "dawn_native/CommandAllocator.h"
 #include "dawn_native/CommandBuffer.h"
 
 #include "common/vulkan_platform.h"
@@ -25,9 +26,11 @@
 
 namespace dawn_native { namespace vulkan {
 
+    class Device;
+
     class CommandBuffer : public CommandBufferBase {
       public:
-        CommandBuffer(CommandBufferBuilder* builder);
+        CommandBuffer(Device* device, CommandEncoderBase* encoder);
         ~CommandBuffer();
 
         void RecordCommands(VkCommandBuffer commands);
diff --git a/src/dawn_native/vulkan/DeviceVk.cpp b/src/dawn_native/vulkan/DeviceVk.cpp
index 48e526c..0b6ff31 100644
--- a/src/dawn_native/vulkan/DeviceVk.cpp
+++ b/src/dawn_native/vulkan/DeviceVk.cpp
@@ -146,8 +146,8 @@
     ResultOrError<BufferBase*> Device::CreateBufferImpl(const BufferDescriptor* descriptor) {
         return new Buffer(this, descriptor);
     }
-    CommandBufferBase* Device::CreateCommandBuffer(CommandBufferBuilder* builder) {
-        return new CommandBuffer(builder);
+    CommandBufferBase* Device::CreateCommandBuffer(CommandEncoderBase* encoder) {
+        return new CommandBuffer(this, encoder);
     }
     ResultOrError<ComputePipelineBase*> Device::CreateComputePipelineImpl(
         const ComputePipelineDescriptor* descriptor) {
diff --git a/src/dawn_native/vulkan/DeviceVk.h b/src/dawn_native/vulkan/DeviceVk.h
index 4d6e035..86653c2 100644
--- a/src/dawn_native/vulkan/DeviceVk.h
+++ b/src/dawn_native/vulkan/DeviceVk.h
@@ -64,7 +64,7 @@
         void AddWaitSemaphore(VkSemaphore semaphore);
 
         // Dawn API
-        CommandBufferBase* CreateCommandBuffer(CommandBufferBuilder* builder) override;
+        CommandBufferBase* CreateCommandBuffer(CommandEncoderBase* encoder) override;
         InputStateBase* CreateInputState(InputStateBuilder* builder) override;
         RenderPassDescriptorBase* CreateRenderPassDescriptor(
             RenderPassDescriptorBuilder* builder) override;