A method includes forming a first composite wafer including molding a plurality of device dies and a plurality of through-vias in a first molding material, and forming redistribution lines on opposite sides of the first molding material. The redistribution lines are inter-coupled through the plurality of through-vias. The method further includes forming a second composite wafer including stacking a plurality of dies to form a plurality of die stacks, and molding the plurality of die stacks in a second molding material. The second molding material fills gaps between the plurality of die stacks. The first composite wafer is bonded to the second composite wafer to form a third composite wafer.